1

If I have a HashMap hashM, an ArrayList arrayL. If I would like to use an if statement to check whether hashM has all the elements in arrayL, how can I do that?

I cm currently using something like

if (hashM.values().containsAll(arrayL.getPreReqs()))

However it doesn't work properly.

Dear all thanks for the answers!

Actually containsAll works however the way I structure the my codes is wrong so that I got wrong outcomes. Now it has been fixed.

Cheers!

Wesley
  • 11
  • 1
  • 2
  • 5

4 Answers4

4

Given

Map<?,?> map = new HashMap<?,?>();
List<?> list = new ArrayList<?>();

The approach you tried (well, nearly, as pointed out by Marko Topolnik) is indeed correct:

if (map.values().containsAll(list)) { ... }

(Or map.keySet().containsAll(list) if you were interested in the map keys instead of values.)

For this to work as expected for custom types, you of course must have implemented equals() and hashcode() correctly for them. (See e.g. this question or better yet, read Item 9 in Effective Java.)

By the way, when working with Java Collections, it is good practice to define fields and variables using the interfaces (such as List, Set, Map), not implementation types (e.g. ArrayList, HashSet, HashMap). For example:

List<String> list = new ArrayList<String>();
Map<Integer, String> map = new HashMap<Integer, String>();

Similarly, a more "correct" or fluent title for your question would have been "How to check whether a Map has all the elements of a List?". Check out the Java Collections tutorial for more info.

Community
  • 1
  • 1
Jonik
  • 80,077
  • 70
  • 264
  • 372
1

Your code is correct except..

if (hashM.values().containsAll(arrayL)) {....}

[EDIT] You can use HashMap.containsValue(Object value)

public boolean containsList(HashMap<K, V> map, List<V> list) {
    for(V value : list) {
       if(!map.containsValue(value)) {
          return false;
       }
    }
    return true;
}
Mitesh Pathak
  • 1,306
  • 10
  • 14
1

Your code should work - but will not be particularly efficient. You need to compare every element in the list with every element in the map.

If (and only if) you can easily extract the key of the map from the elements then you would be better off looping through your List and for each element do map.containsKey(getKey(elem)), this will be much faster.

If you are doing this sort of comparison a lot and you cannot map from element to key then it may be worth keeping a HashSet of the values for this purpose.

Tim B
  • 40,716
  • 16
  • 83
  • 128
-1

I agree with JoniK. This can be done in a single line like this.

if(hashM.values().containsAll(arrayL)) {// put your code here that will be returned}
Qadir Hussain
  • 1,263
  • 1
  • 10
  • 26