将HashMap的键和值组合到集合中 [英] Combine keys and values of a HashMap to a Set

查看:61
本文介绍了将HashMap的键和值组合到集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashMap<Integer, Integer>,唯一键可以有重复的值.有没有一种方法可以将HashMap转换为包含键和值的唯一整数的Set<Integer>.

I have a HashMap<Integer, Integer>, There can be duplicate values for the unique keys. Is there a way to convert the HashMap to a Set<Integer> which contains unique Integers of both the keys and values.

绝对可以通过迭代keySet()和.values()在两个循环中完成.我想知道在Java 8流中是否可行.

This can definitely be done in two loops by iterating over the keySet() and .values(). I'm would like to know whether this is possible in java 8 streams.

推荐答案

您可以使用流函数来组合值和键:

You can use the stream function to combine both the values and the keys:

Map<Integer, Integer> map = ...
Set<Integer> total = Stream.concat(
     map.keySet().stream(), 
     map.values().stream()
).collect(Collectors.toSet());

这使用地图的keySet().stream()values().stream()获取两者的流,然后使用

This uses the map's keySet().stream() and values().stream() to get a stream of both, then connects them using Stream.concat, then finally turns it into a set. The call to .toSet() prevents duplicate elements, because a set cannot contain duplicate elements.

如果键是双精度键,并且值是浮点数,则也可以使用此技巧.在这种情况下,java将提供最大的公共除法器类,在这种情况下为Number.

This trick can also be used if the keys are double, and the values are floats, in this case java will give the greatest common divider class back, what in this case is Number.

这篇关于将HashMap的键和值组合到集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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