例如,我们有一个Map<Integer, Integer[]>
,键是配送人,值是订单号,并且Map.values是不重复的,为了查找方便,我们要调转键值,将其转换为Map<Integer, Integer>
,其中键是订单号,值为配送人,我们可以这么做:
Map<Integer, Integer[]> map = new HashMap<>(); map.put(1, new Integer[] { 30, 40, 50}); map.put(2, new Integer[] { 60, 70, 80}); Map<Integer[], Integer> map2 = map.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); Map<Integer, Integer> map3 = map2.entrySet().stream() .flatMap(entry -> Arrays.stream(entry.getKey()).map(e2 -> new AbstractMap.SimpleEntry<>(e2, entry.getValue()))) .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));
还可以简化成这样:
Map<Integer, Integer[]> map = new HashMap<>(); map.put(1, new Integer[] { 30, 40, 50}); map.put(2, new Integer[] { 60, 70, 80}); Map<Integer, Integer> map2 = map.entrySet().stream() .flatMap(entry -> Arrays.stream(entry.getValue()).map(v -> new AbstractMap.SimpleEntry<>(v, entry.getKey()))) .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));