In a Java class I have a method to reOrder an existing HashMap by date. The HashMap is of a type
where the Object contains a field called exp
For simplicity I am assuming that type of your map is something more like Map
where MyClass
has method like getDate()
which returns expPayDate
.
My issue is what is the best way to determine the item with the newest date.
If you want to find single map entry which value contains max date you don't need to sort entire map which at best would give you O(n*logn). What you need is simple iteration of all elements in map and comparing them with current max, which will be O(n) operation.
You can use stream()
(functionality added in Java 8) and its max
method. This method needs Comparator
and you can easily create one by using comparing
method and passing lambda expression which will return value which should be used when comparing.
So your code can look like
//import java.util.Map.Entry;
Optional> max = map.entrySet().stream()
.max(Comparator.comparing(e -> e.getValue().getDate()));
Entry entry = max.get();
MyClass maxMC = entry.getValue();
If you can't use Java 8 you can write your own method which will iterate over elements and find max. Such method can look like
public static T max(Iterable iterable, Comparator comp) {
Iterator it = iterable.iterator();
T max = null;
if (it.hasNext()) {
max = it.next();
}
while (it.hasNext()) {
T tmp = it.next();
if (comp.compare(max, tmp) < 0)
max = tmp;
}
return max;
}
and you can use it like
Comparator> myComparator = new Comparator>() {
@Override
public int compare(Entry o1, Entry o2) {
return o1.getValue().getDate().compareTo(o2.getValue().getDate());
}
};
Entry maxEntry = max(map.entrySet(), myComparator);
MyClass max = maxEntry.getValue();