Reputation: 386
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?
Upvotes: 15
Views: 28417
Reputation: 140309
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());
Upvotes: 36
Reputation: 35795
SortedSet
Depending on your application you can think about using a SortedSet
(like TreeSet
). This allows you to change the collection and always receive the lowest element easily.
Adding elements to the collection is more expensive, though.
Upvotes: 0
Reputation: 48258
If you dont mind to change the insertion order then sort the list and get the elemeent at index 0
Upvotes: -1