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.
.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
.
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