Get value from Map of Map of Map without null pointer exception

Viewed 622

I have

Map<String, Map<String, Time>> map = new HashMap<String, Map<String, Time>>();
Time t = map.get("key1").get("key2"); 

Is there any way using lambda to get the value of Time t without NullPointerException in between. So if key1 return null value then t should null and code should not throw null pointer

2 Answers

Use getOrDefault introduced in Java8 with your key and Collections.emptyMap() as the default value. Here's how it looks.

Time t = map.getOrDefault("key1", Collections.emptyMap()).get("key2");

In Java 8

Time t = Optional.ofNullable(map.get("key1"))
            .map(m -> m.get("key2"))
            .orElse(null);
Related