Java 8 nonNull threads on object properties

I have the following snippet that collects certain objects that have a row property namethat 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 if there is a more elegant way to write in a if-statementfunctional way and it is better to check empty or null properties than have a conditional block in the filter.

+4
source share
3 answers

Replace the second filteras follows:

.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)
 })
+7
source

Go for a functional style to express the result:

.filter(foo -> foo.getName() != null && foo.getName().contains(filterName))

:

.filter(foo -> foo.getName() != null)
.filter(foo -> foo.getName().contains(filterName))

Foo:: getName (Objects:: isNull) , .

filterName , Strings.isEmptyOrNull .

+1

If you have access to the Foo Class, move the if conditions to the method isSameNameand use the filter as shown below

filter(myFoo -> {return myFoo.isSameName(filterName);})
0
source

Source: https://habr.com/ru/post/1651646/


All Articles