I have about 8 date variables (java.util.Date) with different variable names. What's the most efficient/best way of choosing the most recent (max) of these dates?
-
just once. all date variable values may be different. I'm just trying to find the most recent date efficiently for displaying on a jsp page.– user6123723Commented Apr 12, 2012 at 17:14
-
Is the most recent always the max or do you need to account for future dates?– eabrahamCommented Apr 12, 2012 at 17:27
-
the most recent is the max. All dates are past dates.– user6123723Commented Apr 12, 2012 at 17:56
5 Answers
Ideally, store them in a collection - this might make sense in terms of your program design anyway. If you have e.g. a List object, you can do:
Collections.max(dates);
Since you're storing all your dates in different variables, you need to do something like the following varargs function and pass all your variables off to it:
protected Date getMostRecentDate(Date ... dates) {
Arrays.sort(dates);
return myDateArray[dates.length - 1];
}
Then you'd call it like so:
Date mostRecent = getMostRecentDate(date1, date2, date3 /* etc.*/);
-
This is not efficient since he only wants to get the maximum once. Sorting takes O(N*logN) while a single max operation is O(N).– TudorCommented Apr 12, 2012 at 17:18
-
@Tudor sure, though in all fairness, with small N (and i'm assuming that he's got small N b/c otherwise maintaining a whole bunch of different fields is going to be a lot of work), there's not going to be much difference.– stevevlsCommented Apr 12, 2012 at 17:20
Date
is comparable, so add them all to a list, and use Collections.max()
to find the greatest (latest) date:
List<Date> dates = new ArrayList<Date>();
dates.add(foo);
dates.add(bar);
... etc
Date latest = Collections.max(list);
Actually, if you wanted to get fancy, you could do this:
public static <T extends Comparable<T>> T max(T... items) {
return Collections.max(Arrays.asList(items));
}
And call it like this:
Date latest = MyClass.max(foo, bar, fred);
But it will also work for any Comparable
:
Integer biggest = MyClass.max(3, 7, 4, 1);
-
2
Add them all to a collection and then sort it, or add them to a collection that's ordered in the first place, such as PriorityQueue:
PriorityQueue<Date> dateQ = new PriorityQueue<Date>();
dateQ.add(someDate);
dateQ.add(anotherDate);
dateQ.add(thirdDate); // etc...
System.out.println("Max date is: " + dateQ.peek());
-
How does the efficiency of this compare to an implementation with a regular collection? Commented Apr 12, 2012 at 17:35
-
1Good question. This should be O(N log N), same as adding it to a list and then sorting. However, Collections.max (as referenced in several other answers) is O(N) so that's definitely more efficient than my answer. Commented Apr 12, 2012 at 17:48