Using streams to convert a list of objects into a string obtained from the toString method

One simple way is to append your list items in a StringBuilder

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

StringBuilder b = new StringBuilder();
list.forEach(b::append);

System.out.println(b);

you can also try:

String s = list.stream().map(e -> e.toString()).reduce("", String::concat);

Explanation: map converts Integer stream to String stream, then its reduced as concatenation of all the elements.

Note: This is normal reduction which performs in O(n2)

for better performance use a StringBuilder or mutable reduction similar to F. Böller’s answer.

String s = list.stream().map(Object::toString).collect(Collectors.joining(","));

Ref: Stream Reduction

Leave a Comment