簡體   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