Search code examples
javalambdajava-8hashmapcontains

Java: Map Contains Equals to or Less Than of Another Map


How do I check if 1 subset contains less than or equal to of another subset? SMap and TMap below.

In this example, doing equation returns false.

sMap.entrySet().containsAll(tMap.entrySet())

I believe it returns false, since it is trying equal the count of A,B,C. {1,2,2} does Not equal {1,1,1}. However, it should be true since {1,1,1} <= {1,2,2} for each element A,B,C.

Is there an easy method to doing a contains less than or equal to? Otherwise I will just write a manual for loop with count.

enter image description here

Check whether a map contains all contents of another map

Verify that all key/value pairs in a Map are present in another Map


Solution

  • As I know, there is no built-in method to do what you desire, containsAll returns true when all the map entries from one map exist in another map.

    But, as you said you can write such a method as below;

    private static boolean containsAllCounts(Map<String, Integer> firstMap, Map<String, Integer> secondMap) {
        String key;
        int secondMapCount;
        for (Map.Entry<String, Integer> entry : secondMap.entrySet()) {
            key = entry.getKey();
            secondMapCount = entry.getValue();
            if (!firstMap.containsKey(key) || firstMap.get(key) <= secondMapCount) {
                return false;
            }
        }
        return true;
    }
    

    When there are two maps as below;

        Map<String, Integer> firstMap = new HashMap<>();
        firstMap.put("A", 2);
        firstMap.put("B", 2);
        firstMap.put("C", 1);
    
        Map<String, Integer> secondMap = new HashMap<>();
        secondMap.put("A", 1);
        secondMap.put("B", 1);
    
        System.out.println(containsAllCounts(firstMap, secondMap));
        System.out.println(containsAllCounts(secondMap, firstMap));
    

    Outputs will be;

    true
    false