Search code examples
javadictionaryhashmapsetjava-stream

How to Compare a Key of a HashMap with a Set?


I have a HashMap:

HashMap<Integer,Integer> hashMap = new HashMap<Integer,Integer>();

And a Set of Sets:

Set<Set<Integer>> set = Set.of(Set.of(0, 1, 2), Set.of(3, 4, 5));

I want to check if 3 of the Keys of the HashMap contain 3 Elements of the Set and if so check if the values are equal.

for example :

hashMap.put(0,1);
hashMap.put(1,1);
hashMap.put(2,1);
return true;

hashMap.put(4,2);
hashMap.put(5,2);
hashMap.put(12,2);
return false;

is there a possible solution with stream()?


Solution

  • First, I'd go over the map entries and make sure they all match the keys, since this can be checked regardless of the set. You can achieve this by streaming the entries and using allMatch. Then, you can stream over the sets, and for each of them check it's the same size of the map and all the keys match:

    return hashMap.entrySet()
                  .stream()
                  .allMatch(e -> e.getKey().equals(e.getValue())) &&
           set.stream()
              .anyMatch(s -> s.size() == hashMap.size() && s.containsAll(hashMap.keySet()));