I am using Java 8
method1()
-> returns a Map<String,Map<String,Set<String>>>
.
If I chain the method calls this way -> method1().get("A").get("B")
a NullPointerException
could happen.
So I am using the following strategy to avoid using the traditional if( != null)
code:
Optional.ofNullable(method1()).map(x -> x.get("A")).map(y -> y.get("B"))
but the this code return an Optional
and I need that returns the Set<String>
.
How can I cast it, and in case of null
(in the case of the get methods returns null) how returns null
?
Thanks in advance.
CodePudding user response:
use orElse like
Set<String> result = Optional.ofNullable(method1())
.map(x -> x.get("A"))
.map(y -> y.get("B"))
.orElse(null);
CodePudding user response:
Polishing the code by gamgoon a little bit:
Set<String> result = Optional.of(method1())
.map(x -> x.get("A"))
.map(y -> y.get("B"))
.orElse(Collections.emptySet());
System.out.println(result);
Output in case either key is not in a map where looked up:
[]
You may recognize the result of printing an empty collection. In places where you want a collection, you should not accept a null
. Use an empty collection to signify that there are no elements. In the same vein I have assumed that your method1()
may return an empty map but not null
. So we don’t need ofNullable()
when converting into an Optional
— the simple of()
is fine.