How to get the most recent of a set of date variables in java
-
31-05-2021 - |
سؤال
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?
المحلول
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);
نصائح أخرى
Put them in a List and use Collections.max
.
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.*/);
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);
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());