从 HashMap 的键中获取 HashSet?
我有一个相当大的(100'000 个条目)HashMap
。现在,我需要一个包含此 HashMap 中所有键的 HashSet
。不幸的是,HashMap
只有一个 keySet()
方法,它返回一个 Set
,而不是 HashSet
。
使用 Java 生成此类 HashSet
的有效方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么特别需要 HashSet?
任何 Set 都具有相同的接口,因此通常可以互换使用,因为良好实践要求您对所有 Set 都使用 Set 接口。
如果您确实需要,您可以从另一个创建一个。对于通用代码,它可能是:
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:
假设“高效”一词是您问题的关键部分,并且根据您想要对集合执行的操作,创建您自己的 HashSet 子类可能是一个想法,它会忽略 HashSet 实现并呈现现有的视图地图,代替。
作为部分实现的示例,它可能看起来像这样:
如果您不知道如何使用该类,则需要注意重写所有相关方法。
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.
As a partially implemented example, it might look something like:
If you don't know how the class will be used, you'll need to take care to override all the relevant methods.
没试过。
Haven't tried it.
您不能从现有的
Set
创建HashSet
吗?但是(更重要的是)您为什么担心从keySet()
方法返回给您的实现?Can you not create the
HashSet
from an existingSet
? But (more importantly) why are you worried about the implementation returned to you from thekeySet()
method ?设置 set=new HashSet(map.keySet());
Set set=new HashSet(map.keySet());