Lucian Enache Lucian Enache - 11 months ago 58
Java Question

Java 8 streams nonNull on properties of objects

I have the following snippet that collects specific objects which have a

string property that contains a specific filter

List<Foo> filteredFoo=
.filter(myFoo -> {
if (Strings.isNullOrEmpty(myFoo.getName()))
return false;
return myFoo.getName().contains(filterName);

It works as expected but I was wondering whether is there a more elegant way to write the
in a functional way and check for empty or null properties in a nicer fashion than having the conditional block in the filter.

Answer Source

Replace second filter with following:

.filter(myFoo -> Optional.ofNullable(myFoo.getName())
                         .filter(n -> n.contains(filterName))

or even:

.filter(myFoo -> {
    String name = myFoo.getName();
    return name != null && name.contains(filterName)