User
User

Reputation: 67

Concatenate list of ints in java 8

How can I concatenate list of ints

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
Optional<Integer> result = numbers.stream().reduce((subtotal, element)-> Integer.valueOf(subtotal + ", " + element));

But I got an exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1, 2" at java.lang.NumberFormatException.forInputString(Unknown Source)

Upvotes: 1

Views: 11016

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40078

If you wanna do it using reduce convert Integers into Strings and then use Accumulator function

Optional<String> result = numbers.stream().map(i->i.toString()).reduce((i,j)->i+", "+j);

Or you can simply use Collectors.joining

String str = numbers.stream().map(i->i.toString()).collect(Collectors.joining(", "));

Upvotes: 10

Andronicus
Andronicus

Reputation: 26056

You can use String.join for that. It joins given Iterable of CharSequence with specified delimiter (", " in your case):

List<String> strings = numbers.stream().map(Object::toString).collect(Collectors.toList())

String concatenated = String.join(", ", strings)

Upvotes: 4

Related Questions