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.

BeginnersSake
  • 650
  • 2
  • 18
  • 30

1 Answers1

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

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 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. – holi-java Jul 21 '17 at 13:03
  • 1
    I had no idea about `Objects` class. Thanks to you now I know. – BeginnersSake Jul 21 '17 at 13:03
  • 4
    …and I recommend replacing `max(Date::compareTo)` with `max(Comparator.naturalOrder())`. – Holger Jul 21 '17 at 13:06