Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the earliest date of a List in Java?

Tags:

java

date

compare

I have an ArrayList which stores 0...4 Dates.

The amount of Dates in the list depends on a Business logic.

How can I get the earliest date of this list? Of course I can build iterative loops to finally retrieve the earliest date. But is there a 'cleaner'/ quicker way of doing this, especially when considering that this list can grow on a later perspective?

like image 686
mffm Avatar asked Sep 30 '16 12:09

mffm


Video Answer


1 Answers

java.util.Date implements Comparable<Date>, so you can simply use:

Date minDate = Collections.min(listOfDates);

This relies on there being at least one element in the list. If the list might be empty (amongst many other approaches):

Optional<Date> minDate = listOfDates.stream().min(Comparator.naturalOrder());
like image 132
Andy Turner Avatar answered Oct 16 '22 13:10

Andy Turner