Replace this lambda with a reference to the "Objects :: nonNull" method

I wrote some code to find the last date from a list of an object that contains a Date variable.

list.stream().map(segment -> segment.lastLoad).filter(x->x!=null).max(Date::compareTo).get()

But I get a sonar message that says

Replace this lambda with a reference to the Objects :: nonNull method.

What I can't figure out is where I can use the method link provided in the sonar lint question.

+3


source to share


1 answer


.filter(x->x!=null) == .filter(Objects::nonNull)

      

Interestingly, you already used the method reference in (but haven't seen this one):

max(Date::compareTo)

      



Also you are obviously returning Date

, but from Optional<Date>

you you should get a warning (if using IDEA) that it is not safe to call get

directly on Optional

.

And you can also replace that max(Date::compareTo)

with max(Comparator.naturalOrder())

, since Date

already Comparable

.

+6


source







All Articles