Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The min non-null LocalDateTime of a list using stream

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?

like image 441
ycomp Avatar asked Sep 13 '17 07:09

ycomp


People also ask

How do you find the maximum and minimum of a stream?

To get max or min date from a stream of dates, you can use Comparator. comparing( LocalDate::toEpochDay ) Comparator. The toEpochDay() function returns the count of days since epoch i.e. 1970-01-01.

How do I get LocalDateTime in Java 8?

We can use now() method to get the current date. We can also provide input arguments for year, month and date to create LocalDate instance. This class provides an overloaded method for now() where we can pass ZoneId for getting dates in a specific time zone. This class provides the same functionality as java.

How do I use LocalDateTime?

Methods of Java LocalDateTimeIt is used to get the value of the specified field from this date-time as an int. It is used to return a copy of this LocalDateTime with the specified number of days subtracted. It is used to obtain the current date-time from the system clock in the default time-zone.

What is the difference between LocalDate and LocalDateTime?

LocalDate – represents a date (year, month, day) LocalDateTime – same as LocalDate, but includes time with nanosecond precision.


1 Answers

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)

like image 90
Eugene Avatar answered Oct 06 '22 00:10

Eugene