Using streams 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 = list.stream().mapToInt(AClass::getValue).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 = list.stream().... //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".

13 Answers
13

Leave a Comment