从HashMap的键中获取HashSet? [英] Get a HashSet out of the keys of a HashMap?

查看:114
本文介绍了从HashMap的键中获取HashSet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的(100,000个条目) HashMap 。现在,我需要包含 HashMap 中所有键的 HashSet 。不幸的是, HashMap 只有一个 keySet()方法,它返回一个 Set $ 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屋!

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