首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java8流:如何使用Map<String (.)将List<Integer>>、List<Integer>>转换为Map<Integer、List<String>>

问Java8流:如何使用Map<String (.)将List<Integer>>、List<Integer>>转换为Map<Integer、List<String>>
EN

Stack Overflow用户
提问于 2021-07-02 13:34:28
回答 1查看 72关注 0票数 0

我有一张地图如下:

代码语言:javascript
复制
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);

这使产出如下:

代码语言:javascript
复制
{city1=[1, 2, 3], city2=[1, 4, 3, 5], city3=[6, 2, 3, 5, 7]} 

我想用流对城市进行分类,按照它们的Map<Integer, List<String>>这样的精确编码来分组。

代码语言:javascript
复制
{1 = ["city1", "city2"], 2 =["city1", "city3"], 3 = ["city1","city2", "city3"] ...}  
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-02 14:12:28

数据

代码语言:javascript
复制
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));

把你当前的城市地图精确编码,然后:

  • 流源地图的条目集(
  • )创建单独的pincode条目,城市
  • 使用这些条目来使用groupingBy

填充新地图。

代码语言:javascript
复制
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);

打印

代码语言:javascript
复制
1=[city2, city1]
2=[city3, city1]
3=[city3, city2, city1]
4=[city2]
5=[city3, city2]
6=[city3]
7=[city3]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68226144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档