java - Advantages of using a (flat)map over a simple null check? -


i reading below source, , wondering why on earth i'd use flatmap way. see lot more objects instantiated, code executed in simple null check via if statement, terminate on first null , not bother check others , fits nice , neatly in wrapper.

as see if check faster + more memory safe(the speed crucial me have 2-3 milliseconds lot of code execute, if @ all)

what advantages of using "(flat)map" optional way? why should consider switching it?

from http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

class outer {     nested nested; }  class nested {     inner inner; }  class inner {     string foo; } 

in order resolve inner string foo of outer instance have add multiple null checks prevent possible nullpointerexceptions:

outer outer = new outer(); if (outer != null && outer.nested != null && outer.nested.inner != null) {     system.out.println(outer.nested.inner.foo); } 

the same behavior can obtained utilizing optionals flatmap operation:

optional.of(new outer())     .flatmap(o -> optional.ofnullable(o.nested))     .flatmap(n -> optional.ofnullable(n.inner))     .flatmap(i -> optional.ofnullable(i.foo))     .ifpresent(system.out::println); 

i think optional's use clearer in wider streaming context, not 1 liner.

suppose dealing arraylist of outers called items , requirement stream of foo strings if present.

we this:

//bad example, read on stream<string> allfoos = list.stream()             .filter(o -> o != null && o.nested != null && o.nested.inner != null)             .map(o -> o.nested.inner.foo); 

but i've had repeat myself, how string outer (o != null && o.nested != null && o.nested.inner != null , o.nested.inner.foo)

stream<string> allfoos =         list.stream()                 .map(o -> optional.ofnullable(o)                         .map(t -> t.nested)                         .map(n -> n.inner)                         .map(i -> i.foo))                 .filter(s -> s.ispresent())                 .map(s -> s.get()); 

this gives me easy way insert default values:

stream<string> allfoos =             list.stream()                     .map(o -> optional.ofnullable(o)                             .map(t -> t.nested)                             .map(n -> n.inner)                             .map(i -> i.foo)                             .orelse("missing")); 

the alternative might this:

//bad example (imo) stream<string> allfoos = list.stream()             .map(o -> o != null && o.nested != null && o.nested.inner != null ?                     o.nested.inner.foo : "missing"); 

Comments

Popular posts from this blog

ruby on rails - Permission denied @ sys_fail2 - (D:/RoR/projects/grp/public/uploads/ -

c++ - nodejs socket.io closes connection before upgrading to websocket -

java - What is the equivalent of @Value in CDI world? -