Minimum non-zero LocalDateTime list using stream

I know how to get min LocalDateTimefrom a list thanks to: https://stackoverflow.com/a/3166/

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

My problem is a little different though ...

  • I would like min LocalDateTimenotnull
  • or nullif all of themnull

How will I do this in a concise manner?

+4
source share
2 answers

You can simply do:

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

And the value absentindicates that there are only zeros in your list (or your list is empty)

+7
source

Something like this, maybe?

LocalDateTime minDate = list.stream()
    .filter(Objects::nonNull)
    .map(u -> u.date)
    .min(LocalDateTime::compareTo)
    .orElse(null);
+3
source

Source: https://habr.com/ru/post/1685577/


All Articles