7

I know how to get the min LocalDateTime of a list thanks to: https://stackoverflow.com/a/20996009/270143

e.g. LocalDateTime minLdt = list.stream().map(u -> u.getMyLocalDateTime()).min(LocalDateTime::compareTo).get();

My problem is slightly different though...

  1. I would like the min LocalDateTime that is not null
  2. or null if they are all null

How would I go about doing that in a concise way?

ycomp
  • 8,316
  • 19
  • 57
  • 95

2 Answers2

9

You could simply do:

Optional<LocalDateTime> op = list.stream()
        .filter(Objects::nonNull)
        .min(Comparator.naturalOrder());

And the absent value would indicate that there are only nulls in your List (or your List is empty)

Eugene
  • 117,005
  • 15
  • 201
  • 306
4

Something like this, maybe?

LocalDateTime minDate = list.stream()
    .filter(Objects::nonNull)
    .map(u -> u.date)
    .min(LocalDateTime::compareTo)
    .orElse(null);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
  • ah I guess I can just use the `Optional` being empty to indicate `null` – ycomp Sep 13 '17 at 07:12
  • 1
    @HubertGrzeskowiak probably `orElse(null)` instead of `get`, since the OP wants a `null` when all are null in the List – Eugene Sep 13 '17 at 07:15
  • 2
    Just a side note, when the element type implement `Comparable`, it’s preferable to use the existing `Comparator.naturalOrder()` instead of creating a new comparator via `ComparableType::compareTo`… – Holger Sep 13 '17 at 07:59