检查ArrayList Java中存在的地图密钥

发布于 2025-02-13 11:58:28 字数 464 浏览 1 评论 0原文

想检查阵列列表中的hashmap的键是否存在。

尝试了下面的操作,它可以正常工作,但想知道是否还有其他更好的解决方案。

public boolean check(Map<String, String> map) {
        Collection<String> list = new ArrayList<String>();
        list.add("One");
        list.add("Two");
        list.add("Three");
    
        for(String key: map.keySet()) {
            if(!list.contains(key)) {
                return false;
            }
        }
        return true;
    }

Wanted to check if the keys of the hashmap is present in the arrayList.

Tried the below and it working, but wanted to know if there are any other better solution.

public boolean check(Map<String, String> map) {
        Collection<String> list = new ArrayList<String>();
        list.add("One");
        list.add("Two");
        list.add("Three");
    
        for(String key: map.keySet()) {
            if(!list.contains(key)) {
                return false;
            }
        }
        return true;
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

情绪少女 2025-02-20 11:58:28

您可以使用 collection.containsall() 也将@oh上帝蜘蛛归功于他们在几乎在同一第二个评论中提到的):

return list.containsAll(map.keySet());

You can use Collection.containsAll() (also credits to @OH GOD SPIDERS since they mentioned it in the comments almost in the same second) :

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