Java 8: How to convert List to Map>?

前端 未结 5 1620
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 17:25

I have a List of String like:

List locations = Arrays.asList(\"US:5423\",\"US:6321\",\"CA:1326\",\"AU:5631\");

And I want to

5条回答
  •  天涯浪人
    2021-01-01 18:02

    What about POJO. It looks not complicated comparing with streams.

    public static Map> groupByCountry(List locations) {
        Map> map = new HashMap<>();
    
        locations.forEach(location -> {
            String[] parts = location.split(":");
            map.compute(parts[0], (country, codes) -> {
                codes = codes == null ? new HashSet<>() : codes;
                codes.add(parts[1]);
                return codes;
            });
        });
    
        return map;
    }
    

提交回复
热议问题