Check map key present in arraylist java

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;
    }

Upvotes: 0

Views: 315

Answers (1)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 29028

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

Upvotes: 2

Related Questions