15

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?

1
  • @AndyTurner , you should post this comment as an answer. Commented Sep 30, 2016 at 12:17

3 Answers 3

36

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());
0

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.

-1

If you dont mind to change the insertion order then sort the list and get the elemeent at index 0

1
  • 2
    Sorting the list is an O(n log n) operation. You can find the minimum element in O(n) simply by iterating the list. Commented Sep 30, 2016 at 12:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.