Search code examples
javahashmap

Java Map - log message when key is not found in getOrDefault


I have a Map<String, List<SomeClass>> someMap and I'm retrieving the value based on someKey and for each element of the list of SomeClass I'm performing other operations.

someMap.getOrDefault(someKey, new ArrayList<>()).forEach(...)

I also want to be able to log messages when I don't find someKey. How would I be able to achieve it optimally? Is there any other function/way to achieve this behavior?


Solution

  • Map<String, List<String>> map = new HashMap<>();
    List<String> l = new ArrayList<>();
    l.add("b");
    map.put("a", l);
    

    Yes, you can do it in a single statement. Use .compute().

    map.compute("a", (k, v) -> {
        if (v == null) {
            System.out.println("Key Not Found");
            return new ArrayList<>();
        }
        return v;
    }).forEach(System.out::println);
    

    There's also computeIfAbsent() which will only compute the lambda if the key is not present.


    Note, from the documentation:

    Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

    This will add the key which was not found in your map.

    If you want to remove those keys later, then simply add those keys to a list inside the if and remove them in one statement like this:

    map.keySet().removeAll(listToRemove);