How to get the earliest date in a list in Java?

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

The number of dates in the list depends on the business logic.

How can I get the earliest date of this list? Of course, I can build iterative loops to finally get the earliest date. But is there a โ€œcleanerโ€ / faster way to do this, especially considering that this list could grow in a later perspective?

+5
source share
3 answers

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

 Date minDate = Collections.min(listOfDates); 

It depends on the presence of at least one element in the list.

+13
source

If you do not mind changing the insertion order, sort the list and get an element with index 0

0
source

SortedSet

Depending on your application, you might consider using a SortedSet (e.g. TreeSet ). This allows you to modify the collection and always get the lowest item.

Adding items to a collection is more expensive.

0
source

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


All Articles