How to generalize utility function using method references/java 8

后端 未结 2 1985
陌清茗
陌清茗 2021-01-14 18:46

I\'ve run into a common situation where i have a list of objects and need to generate a comma separated string with a single property, which are then each surrounded by sing

2条回答
  •  被撕碎了的回忆
    2021-01-14 19:45

    Stream.map() and Collectors.joining() are your friends here.

    companies.stream()
             .map(Company::getId)
             .map(s -> "'" + s + "'")
             .collect(joining(","));
    

    You can create a helper method, but in my judgement the above is succinct enough that it isn't worthwhile:

    static  String mapAndJoin(Collection c, Function f){
        return c.stream()
                .map(f)
                .map(s -> "'" + s + "'")
                .collect(joining(","));
    }
    
    mapAndJoin(companies, Company::getId);
    

提交回复
热议问题