How to reference the result of reduce() operation in Java 8?
Note that if you're doing this not for self-education but to actually use it in some production code, you might want to consider the built-in Collectors.joining
collector:
String result = numbers.stream()
.map(Object::toString)
// or
// .map(x -> x.toString()) // exactly the same
// or
// .map(String::valueOf) // handles nulls by turning them to the string "null"
.collect(Collectors.joining(","));
It has several overloads, similar to Scala's mkString
. Still, this collector only accepts CharSequence
s, so you need to convert your values to strings explicitly as a separate map
step.
Additionally, there is the String.join
method, which also works for a collection of CharSequence
s. If you specifically have one of those (e.g. List<String>
), it might be more convenient to use this method rather than converting the collection to a stream first:
List<String> strings = ...;
String result = String.join(",", strings);
// vs
String result = strings.stream().collect(Collectors.joining(","))
If I remember my java correctly, you can declare the argument type as Collection<?>
to be able to pass a collection of any objects.
As to biting the separator off, I think, just .substring(1)
will do what you want.