Lucian Enache Lucian Enache - 3 months ago 9
Java Question

Java 8 streams nonNull on properties of objects

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

name
string property that contains a specific filter
filterName
.

List<Foo> filteredFoo= fooList.stream()
.filter(Objects::nonNull)
.filter(myFoo -> {
if (Strings.isNullOrEmpty(myFoo.getName()))
return false;
return myFoo.getName().contains(filterName);
}
).collect(Collectors.toList());


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

Answer

Replace second filter with following:

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

or even:

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