从HashMap的键中获取HashSet? [英] Get a HashSet out of the keys of a HashMap?
问题描述
我有一个非常大的(100,000个条目) HashMap
。现在,我需要包含 HashMap
中所有键的 HashSet
。不幸的是, HashMap
只有一个 keySet()
方法,它返回一个 Set $ c> $ c>但不是
HashSet
。
生成这样一个<$ c $的有效方法是什么c> HashSet 使用Java?
为什么你特别需要一个HashSet?
任何Set都具有相同的接口,因此通常可以互换使用,因为良好实践要求您为所有接口使用Set接口。 p>
如果您确实需要,您可以从另一个创建一个。对于泛型代码,它可能是:
映射< B,V> map = ...;
HashSet< B> set = new HashSet< B>(map.keySet());
I have a pretty big (100'000s of entries) HashMap
. Now, I need a HashSet
containing all the keys from this HashMap
. Unfortunately, HashMap
only has a keySet()
method which returns a Set
but not a HashSet
.
What would be an efficient way to generate such a HashSet
using Java?
Why do you specifically need a HashSet?
Any Set have the same interface, so typically can be used interchangeably, as good-practices requires that you use the Set interface for all of them.
If you really need so, you could create one from the other. For generic code, it could be:
Map<B, V> map = ...;
HashSet<B> set = new HashSet<B>(map.keySet());
这篇关于从HashMap的键中获取HashSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!