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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With