Search code examples
javadictionaryhashmapiterationhelper

Java Map util method to deep check for containKey?


Does anybody know a Util library which contains something like a Util.deepContains() method? I have to check a map and it's nested entries for a key. I surely can write my own logic but I like to use Utils to keep my code a bit cleaner and save some unit tests.

The map structure is Map<String, Map<String, Object>> where Object can be another Map and so on.


Solution

  • NO, I am not aware of any existing function in a library. However, if there exist any, is it worth to import the whole library because of one use-case only? Feel free to create your own function. Consider the following example map structure:

    {
        map2={
            map3={
                4=4, 
                5=5
            }
        }, 
        map4={
            6=6, 
            7=7
        }
    }
    

    Regardless how many Map<String, Object> are nested, the following recursive function iterates all the values until it finds the correct one. During the comparison, you have to cast from Object to T due to the correct comparison.

    static <T> boolean deepContains(Map<?, ?> map, T item) {
        for (Entry<?, ?> entry: map.entrySet()) {
            final Object value = entry.getValue();
            boolean returned = false;
            if (value instanceof Map<?, ?>) {
                returned = deepContains((Map<?, ?>) value, item);
            } else {
                returned = item.getClass().cast(value).equals(item);
            }
            if (returned) {return true;}
        }
        return false;
    }
    

    Usage:

    boolean result = deepContains(map, "4"); // returns true
    boolean result = deepContains(map, "7"); // returns true
    boolean result = deepContains(map, "8"); // returns false