Search code examples
javajava-8java-stream

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".


Solution

  • 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