Using Java 8 to convert a list of objects into a string obtained from the toString() method


There are a lot of useful new things in Java 8. E.g., I can iterate with a stream over a list of objects and then sum the values from a specific field of the Object's instances. E.g.

public class AClass {
  private int value;
  public int getValue() { return value; }

Integer sum =;

Thus, I'm asking if there is any way to build a String that concatenates the output of the toString() method from the instances in a single line.

List<Integer> list = ...

String concatenated = //concatenate here with toString() method from java.lang.Integer class

Suppose that list contains integers 1, 2 and 3, I expect that concatenated is "123" or "1,2,3".

This question is tagged with java java-8 java-stream

~ Asked on 2014-07-22 08:54:37

The Best Answer is


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

   List<Integer> list = new ArrayList<>();

   StringBuilder b = new StringBuilder();


you can also try:

String s = -> 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 =","));

Ref: Stream Reduction

~ Answered on 2014-07-22 09:07:31


There is a collector joining in the API. It's a static method in Collectors.","))

Not perfect because of the necessary call of toString, but works. Different delimiters are possible.

~ Answered on 2014-07-22 09:56:10

Most Viewed Questions: