通过按键加入两张地图 [英] Join two maps by key

查看:82
本文介绍了通过按键加入两张地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两张地图:

Map<Integer, String> mapOne = {(1,"a"), (2, "b")};
Map<Integer, Double> mapTwo = {(1,10.0), (2,20.0)};

并且我想通过Integer值将此映射合并为一个,因此结果映射为

and I want to combine this maps into one by Integer value, so the result map is

Map<String, Double> mapResult = {("a",10.0), ("b",20.0)};

有什么方法比遍历条目集更容易做到这一点?

Is there any way to do this easier than iterate over entry set?

推荐答案

假定两个映射的键匹配,并且映射具有相同的条目数,使用Java 8可以用以下一行写成一行:

Assuming that the keys of the two maps match and that the maps have the same number of entries, with Java 8 you can write it in one line with:

Map<String, Double> map = mapOne.entrySet().stream()
                            .collect(toMap(e -> e.getValue(),
                                           e -> mapTwo.get(e.getKey())));

因此,您从第一个地图开始并创建一个新地图,其中的键是mapOne的值,而值是mapTwo中的对应值.

So you start from the first map and create a new map where the keys are the values of mapOne and the values are the corresponding values in mapTwo.

从技术上讲,这等效于迭代第一个映射的条目集.

Technically this is somewhat equivalent to iterating over the entry set of the first map though.

注意:需要import static java.util.stream.Collectors.toMap;

这篇关于通过按键加入两张地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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