Reputation: 67
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
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
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