Java 8: How to convert List to Map>?

前端 未结 5 1612
隐瞒了意图╮
隐瞒了意图╮ 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:10

    Seems like your location map needs to be sorted based on keys, you can try the following

    List locations = Arrays.asList("US:5423", "US:6321", "CA:1326", "AU:5631");
    
        Map> locationMap = locations.stream().map(str -> str.split(":"))
                .collect(() -> new TreeMap>(), (map, parts) -> {
                    if (map.get(parts[0]) == null) {
                        List list = new ArrayList<>();
                        list.add(parts[1]);
                        map.put(parts[0], list);
                    } else {
                        map.get(parts[0]).add(parts[1]);
                    }
                }, (map1, map2) -> {
                    map1.putAll(map2);
                });
    
        System.out.println(locationMap); // this outputs {AU=[5631], CA=[1326], US=[5423, 6321]}
    

提交回复
热议问题