我有一张地图如下:
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"] ...} 发布于 2021-07-02 14:12:28
数据
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));把你当前的城市地图精确编码,然后:
填充新地图。
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]https://stackoverflow.com/questions/68226144
复制相似问题