Java 8 流:如何使用 groupingBy(.) 将 Map<String, List<Integer>> 转换为 Map<Integer, List<String>>

Java 8 stream: how to Convert Map<String, List<Integer>> to Map<Integer, List<String>> using groupingBy(.)

我有如下地图:

Map<String, List<Integer>> cityMap = new HashMap<>();
List<Integer> pincodes1 = Arrays.asList(1,2,3);
List<Integer> pincodes2 = Arrays.asList(1,4,3,5);
List<Integer> pincodes3 = Arrays.asList(6,2,3,5,7);
cityMap.putIfAbsent("city1", pincodes1);  
cityMap.putIfAbsent("city2", pincodes2);  
cityMap.putIfAbsent("city3", pincodes3);

输出为:

{city1=[1, 2, 3], city2=[1, 4, 3, 5], city3=[6, 2, 3, 5, 7]} 

我想按密码对城市进行分组,例如 Map<Integer, List<String>> 使用流。

{1 = ["city1", "city2"], 2 =["city1", "city3"], 3 = ["city1","city2", "city3"] ...}  

数据

Map<String, List<Integer>> cities = Map.of("city1",
        List.of(1, 2, 3), "city2", List.of(1, 4, 3, 5),
        "city3", List.of(6, 2, 3, 5, 7));

将您当前的城市地图获取密码并:

  • 流式传输源映射的条目集
  • 创建个人密码和城市条目
  • 使用这些条目通过 groupingBy
  • 填充新地图
Map<Integer, List<String>> map = cities
            .entrySet()          
            .stream()                  // stream entry sets here
            .flatMap(e -> e.getValue() // flatten the following stream
                    .stream()          // of new entry sets
                    .map(pincode -> new AbstractMap.SimpleEntry<>(pincode,e.getKey())))
             // group by key (the pincode of the new entry)
             // and then get the value of the new entry (the city)           
             // and put in a list
            .collect(Collectors.groupingBy(SimpleEntry::getKey,
                Collectors.mapping(SimpleEntry::getValue,
                        Collectors.toList())));

map.entrySet().forEach(System.out::println);

版画

1=[city2, city1]
2=[city3, city1]
3=[city3, city2, city1]
4=[city2]
5=[city3, city2]
6=[city3]
7=[city3]