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

前端 未结 13 1850
太阳男子
太阳男子 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条回答
  •  旧时难觅i
    2020-11-28 02:23

    List list = Arrays.asList("One", "Two", "Three");
        list.stream()
                .reduce("", org.apache.commons.lang3.StringUtils::join);
    

    Or

    List list = Arrays.asList("One", "Two", "Three");
            list.stream()
                    .reduce("", (s1,s2)->s1+s2);
    

    This approach allows you also build a string result from a list of objects Example

    List list = Arrays.asList(w1, w2, w2);
            list.stream()
                    .map(w->w.getStringValue)
                    .reduce("", org.apache.commons.lang3.StringUtils::join);
    

    Here the reduce function allows you to have some initial value to which you want to append new string Example:

     List errors = Arrays.asList("er1", "er2", "er3");
                list.stream()
                        .reduce("Found next errors:", (s1,s2)->s1+s2);
    

提交回复
热议问题