Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashmap

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?

like image 902
here_to_learn Avatar asked Dec 23 '22 17:12

here_to_learn


2 Answers

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);
like image 180
Harshal Parekh Avatar answered Mar 04 '23 18:03

Harshal Parekh


You can create a function to do that. For example, I created a function which will get the value from the map, return it if it is not null, or an empty list otherwise. Before returning the empty list, you can run a Runnable action. The main benefit of that is that you can do more than just logging there.

@Slf4j
public class Main {

    public static Collection<String> retrieveOrRun(Map<String, Collection<String>> map, String key, Runnable runnable) {
        final Collection<String> strings = map.get(key);
        if (strings == null) {
            runnable.run();
            return Collections.emptyList();
        } else {
            return strings;
        }
    }

    public static void main(String[] args) {
        Map<String, Collection<String>> map = new HashMap<>();
        Collection<String> strings = retrieveOrRun(map, "hello", () -> log.warn("Could not find a value for the key : {}", "hello"));
    }
}
like image 20
Mansur Avatar answered Mar 04 '23 18:03

Mansur