从 HashMap 的键中获取 HashSet?

发布于 2024-08-09 03:36:44 字数 252 浏览 1 评论 0原文

我有一个相当大的(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

懷念過去 2024-08-16 03:36:44

为什么特别需要 HashSet?

任何 Set 都具有相同的接口,因此通常可以互换使用,因为良好实践要求您对所有 Set 都使用 Set 接口。


如果您确实需要,您可以从另一个创建一个。对于通用代码,它可能是:

    Map<B, V> map = ...;
    HashSet<B> set = new HashSet<B>(map.keySet());

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());
蓦然回首 2024-08-16 03:36:44

假设“高效”一词是您问题的关键部分,并且根据您想要对集合执行的操作,创建您自己的 HashSet 子类可能是一个想法,它会忽略 HashSet 实现并呈现现有的视图地图,代替。

作为部分实现的示例,它可能看起来像这样:

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... */
}

如果您不知道如何使用该类,则需要注意重写所有相关方法。

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:

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.

罗罗贝儿 2024-08-16 03:36:44
HashSet myHashSet = new HashSet(myHashMap.keySet());

没试过。

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

Haven't tried it.

久而酒知 2024-08-16 03:36:44

您不能从现有的 Set 创建 HashSet 吗?但是(更重要的是)您为什么担心从 keySet() 方法返回给您的实现?

Can you not create the HashSet from an existing Set ? But (more importantly) why are you worried about the implementation returned to you from the keySet() method ?

乖不如嘢 2024-08-16 03:36:44

设置 set=new HashSet(map.keySet());

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文