使用列表值Map< Key,List< Value>>反转Map.映射<值,键>在Java 8中 [英] Invert Map with list value Map<Key, List<Value>> to Map <Value, Key> in Java 8

查看:226
本文介绍了使用列表值Map< Key,List< Value>>反转Map.映射<值,键>在Java 8中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种按键Map<String, List<Integer>>分组值的映射类型,我想还原以便将每个值映射到相应的键

I have a map kind of grouping values by key Map<String, List<Integer>>, i want to revert in order to map each value to the corresponding key

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

Example: I want to transform the code below

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,一千")...

to another Map(Integer, String) where i can find : (1, "UNIT"), (2, "UNIT")...(24, "TEN"), (90, "TEN")...(645, "HUNDRED")...(3456, "THOUSAND")...

推荐答案

您可以使用

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

您可能会认识到与传递给此答案的基于forEach的代码相似. >(累加器)功能.对于顺序执行,它们的操作基本相同,但是此Stream解决方案支持并行处理.这就是为什么它需要其他两个功能来支持创建本地容器并将其合并的原因.

You may recognize the similarity to the forEach based code of this answer within the second function passed to collect (the accumulator) function. For a sequential execution, they do basically the same, but this Stream solution supports parallel processing. That’s why it needs the other two functions, to support creating local containers and to merge them.

另请参见可变减少文档.

这篇关于使用列表值Map&lt; Key,List&lt; Value&gt;&gt;反转Map.映射&lt;值,键&gt;在Java 8中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆