Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 220
Lucian Enache Avatar asked Feb 07 '23 08:02

Lucian Enache


2 Answers

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)
 })
like image 99
Sergii Lagutin Avatar answered Feb 08 '23 23:02

Sergii Lagutin


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.

like image 30
Joop Eggen Avatar answered Feb 08 '23 21:02

Joop Eggen