4

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.

2

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

first, up-vote. I add some shortcut here, if you using IDEA, put your cursor in highlighted part, and then press ALT+ENTER, you then can see optimization options.
I had no idea about Objects class. Thanks to you now I know.
…and I recommend replacing max(Date::compareTo) with max(Comparator.naturalOrder()).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.