简体   繁体   English

从HashMap的键中获取HashSet?

[英]Get a HashSet out of the keys of a HashMap?

I have a pretty big (100'000s of entries) HashMap . 我有一个非常大的(100'000s条目) HashMap Now, I need a HashSet containing all the keys from this HashMap . 现在,我需要一个包含此HashMap中所有键的HashSet Unfortunately, HashMap only has a keySet() method which returns a Set but not a HashSet . 不幸的是, HashMap只有一个keySet()方法,它返回一个Set而不是一个HashSet

What would be an efficient way to generate such a HashSet using Java? 使用Java生成这样一个HashSet的有效方法是什么?

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());

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. 如果您不知道如何使用该类,则需要注意覆盖所有相关方法。

HashSet myHashSet = new HashSet(myHashMap.keySet());

没试过。

Can you not create the HashSet from an existing Set ? 你不能从现有的Set创建HashSet吗? But (more importantly) why are you worried about the implementation returned to you from the keySet() method ? 但是(更重要的是)为什么你担心从keySet()方法返回给你的实现?

Set set = new HashSet(map.keySet());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM