java 从 HashMap 的键中获取 HashSet?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1625814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a HashSet out of the keys of a HashMap?
提问by Haes
I have a pretty big (100'000s of entries) HashMap. Now, I need a HashSetcontaining all the keys from this HashMap. Unfortunately, HashMaponly has a keySet()method which returns a Setbut not a HashSet.
我有一个相当大的(100'000 个条目)HashMap。现在,我需要一个HashSet包含此HashMap. 不幸的是,HashMap只有一个keySet()方法返回 aSet而不是 a HashSet。
What would be an efficient way to generate such a HashSetusing Java?
HashSet使用 Java生成此类的有效方法是什么?
回答by KLE
Why do you specifically need a HashSet?
为什么你特别需要一个 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.
任何 Set 都具有相同的接口,因此通常可以互换使用,因为良好的实践要求您对所有这些都使用 Set 接口。
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());
回答by izb
Assuming that the word 'efficient' is the key part of your question, and depending what you want to do with the set, it might be an idea to create your own subclass of HashSet which ignores the HashSet implementation and presents a view onto the existing map, instead.
假设“高效”这个词是您问题的关键部分,并且取决于您想对集合做什么,那么创建您自己的 HashSet 子类可能是一个想法,它忽略 HashSet 实现并显示现有的视图地图,而不是。
As a partially implemented example, it might look something like:
作为部分实现的示例,它可能看起来像:
public class MapBackedHashSet extends HashSet
{
private HashMap theMap;
public MapBackedHashSet(HashMap theMap)
{
this.theMap = theMap;
}
@Override
public boolean contains(Object o)
{
return theMap.containsKey(o);
}
/* etc... */
}
If you don't know how the class will be used, you'll need to take care to override all the relevant methods.
如果您不知道如何使用该类,则需要注意覆盖所有相关方法。
回答by sinuhepop
HashSet myHashSet = new HashSet(myHashMap.keySet());
Haven't tried it.
没试过
回答by Brian Agnew
Can you not create the HashSetfrom an existing Set? But (more importantly) why are you worried about the implementation returned to you from the keySet()method ?
你不能HashSet从现有的创建Set吗?但是(更重要的是)你为什么担心从keySet()方法返回给你的实现?
回答by Telcontar
Set set=new HashSet(map.keySet());
Set set=new HashSet(map.keySet());

