java - Filter nullable values from stream and updating nullable property -
if have stream<@nullable object>
, can filter null-elements that:
stream<@nullable object> s = str.filter(objects::nonnull);
this, however, returns stream of nullable objects. there elegant way return stream of nonnull elements? @ place know elements can't null.
this i've come with, it's long, imo:
stream<@nonnull object> s = str.map(optional::ofnullable).filter(optional::ispresent).map(optional::get)
(this implies optional::get return nonnull-values)
well, solutions based on optional
or objects
assume checker knows semantics of methods, don’t have explicit annotations.
since filter
never changes type, require deep support checker model stream<@nullable x>
→ stream<@nonnull x>
transition, if understands semantics of filter function.
the simpler approach use map
allows changing element type:
stream<@nonnull object> s = str.filter(objects::nonnull).map(objects::requirenonnull);
here, filter operation ensures there no null
elements, doesn’t change formal element type. in contrast, map
operation allows changing formal type, , function objects::requirenonnull
converts nullable input nonnull output, assuming audit tool knows that, said, these jre provided methods have no annotations.
since requirenonnull
throw exception null
values, combination of filter
, map
allows desired behavior of removing null
values , changing formal element type.
if audit tool not understand semantic of jre method, you’ll have create equivalent method yourself, annotations,
class myobjutil { public static <t> @nonnull t requirenonnull(@nullable t obj) { if(obj==null) throw new nullpointerexception(); return obj; } }
which should recognized correct reasonable checker, , use as
stream<@nonnull object> s = str.filter(objects::nonnull).map(myobjutil::requirenonnull);
your optional
based approach can simplified java 9:
stream<@nonnull object> s = str.flatmap(o -> optional.ofnullable(o).stream());
which can simplified further:
stream<@nonnull object> s = str.flatmap(o -> stream.ofnullable(o));
but of course, again requires tool understanding these methods. or re-implement logic:
class mystreamutil { public static <t> stream<@nonnull t> ofnullable(@nullable t obj) { return obj==null? stream.empty(): stream.of(obj); } }
stream<@nonnull object> s = str.flatmap(o -> mystreamutil.ofnullable(o));
which works under java 8 well.
Comments
Post a Comment