java 8 - Optional<T> does not handle null elements -


as experimented optional<t> not handle null elements, in following example throws nullpointerexception in last statement:

list<string> data = arrays.aslist("foo", null, "bar"); data.stream().findfirst().ifpresent(system.out::println); data.stream().skip(1).findfirst().ifpresent(system.out::println); 

so, still have explicitly deal null , filter non-null elements, such as:

data.stream()     .filter(item -> item != null)     .skip(1)     .findfirst()     .ifpresent(system.out::println); 

is there alternative avoids dealing explicitly null as: item != null

it depends on want do. if want treat null valid value, answer different if want skip nulls.

if want keep "nulls" in stream:

    list<string> data = arrays.aslist("foo", null, "bar");     data.stream().map(optional::ofnullable).findfirst().flatmap(function.identity()).ifpresent(system.out::println);  ;     data.stream().map(optional::ofnullable).skip(1).findfirst().flatmap(function.identity()).ifpresent(system.out::println); 

if want remove nulls stream, use data.stream().filter(objects::nonnull) filter out (or stated o -> o != null, whatever prefer.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -