Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace this lambda with method reference 'Objects::nonNull'

Tags:

java-8

I have written code to find the latest date from a list of an object that contains Date variable.

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

But I am getting sonar issue stating

Replace this lambda with method reference 'Objects::nonNull'.

What I am not able to figure out is where can I use Method reference stated by sonar lint issue.

like image 818
BeginnersSake Avatar asked Dec 23 '22 15:12

BeginnersSake


1 Answers

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

It's interesting that you already use a method reference in(but failed to see this one):

max(Date::compareTo)

Also you are obviously returning a Date but from an Optional<Date>, you should get a warning (if using IDEA) that it's not safe to call get directly on an Optional.

And you could also replace that max(Date::compareTo) with max(Comparator.naturalOrder()) since Date is already Comparable.

like image 92
Eugene Avatar answered Feb 11 '23 18:02

Eugene