在Java 8中将具有列表值Map <key,list <value =“” >>的Map转换为Map <value,key =“”>

时间:2019-01-09 15:44:47

标签: java java-8 java-stream

我有一种通过键Map<String, List<Integer>>对值进行分组的映射,我想还原以将每个值映射到相应的键

示例:我要转换下面的代码

Map<String, List<Integer>> mapOfIntList = new HashMap<String, List<Integer>>();

mapOfIntList.put("UNIT", Arrays.asList(1, 2, 3, 8, 7, 0, 8, 6));
mapOfIntList.put("TEN", Arrays.asList(24, 90, 63, 87));
mapOfIntList.put("HUNDRED", Arrays.asList(645, 457, 306, 762));
mapOfIntList.put("THOUSAND", Arrays.asList(1234, 3456, 5340, 9876));

到另一个我可以找到的Map(Integer,String): (1,“ UNIT”),(2,“ UNIT”)...(24,“ TEN”),(90,“ TEN”)...(645,“ HUNDRED”)...(3456,“一千”)...

4 个答案:

答案 0 :(得分:9)

您可以使用

Map<Integer, String> mapNumberToType = mapOfIntList.entrySet().stream()
    .collect(HashMap::new, (m,e)->e.getValue().forEach(v->m.put(v,e.getKey())), Map::putAll);

您可能会认识到传递给forEach(累加器)函数的第二个函数与this answer的基于collect的代码的相似性。对于顺序执行,它们基本相同,但是此Stream解决方案支持并行处理。因此,它需要其他两个功能来支持创建本地容器并将其合并。

另请参阅文档的Mutable reduction部分。

答案 1 :(得分:6)

或使用两个嵌套的forEach

mapOfIntList.forEach((key, value) ->
            value.forEach(v -> {
                mapNumberToType.put(v, key);
            })
 );

@nullpointer在单线评论中

mapOfIntList.forEach((key, value) -> value.forEach(v -> mapNumberToType.put(v, key)));

答案 2 :(得分:4)

我找到了解决方法:

Map<Integer, String> mapNumberToType = mapOfIntList
    .entrySet()
    .stream()
    .flatMap(
            entry -> entry.getValue().stream()
                    .map(number -> Pair.of(number, entry.getKey()))
                    .collect(Collectors.toList()).stream())
    .collect(
            Collectors.toMap(Pair::getLeft,
                    Pair::getRight, (a, b) -> {
                        return a;
                    }));

System.out.println("Number/Type correspondance : " + mapNumberToType);

希望这可以帮助遇到相同问题的任何人!

答案 3 :(得分:2)

这会更简单:

 source.entrySet()
       .stream()
       .flatMap(e -> e.getValue().stream().map(s -> new AbstractMap.SimpleEntry<>(s, e.getKey())))
       .collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (l, r) -> l));
相关问题