繁体   English   中英

Java 8 流:如何转换地图<String, List<Integer> &gt; 到地图<Integer, List<String> &gt; 使用 groupingBy(.)

[英]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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM