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.
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)
 })
                        Go for the functional style, for the result expression:
.filter(foo -> foo.getName() != null && foo.getName().contains(filterName))
Splitting would not bring more simplicity:
.filter(foo -> foo.getName() != null)
.filter(foo -> foo.getName().contains(filterName))
Using predicates on Foo::getName (Objects::isNull) is senseless complicated too, just in order to spare a variable.
If filterName is not empty itself, Strings.isEmptyOrNull is not needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With