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...
LocalDateTime
that is not null
null
if they are all null
How would I go about doing that in a concise way?
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.
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.
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.
LocalDate – represents a date (year, month, day) LocalDateTime – same as LocalDate, but includes time with nanosecond precision.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With