Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 486
JavaBuilder Avatar asked Jan 01 '23 04:01

JavaBuilder


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");
like image 162
Ravindra Ranwala Avatar answered Jan 02 '23 16:01

Ravindra Ranwala


In Java 8

Time t = Optional.ofNullable(map.get("key1"))
            .map(m -> m.get("key2"))
            .orElse(null);
like image 26
Nikolai Shevchenko Avatar answered Jan 02 '23 17:01

Nikolai Shevchenko