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

前端 未结 13 1793
太阳男子
太阳男子 2020-11-28 02:02

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

13条回答
  •  一生所求
    2020-11-28 02:23

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

       List 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

提交回复
热议问题