I have a TreeMap with String keys and instances of a Class as values. I want to be able to sort on an object of the Class. I have gotten this far:
public class StockTakeCompare {
public static TreeMap<String, StockItem> sortByValues(final Map<String, StockItem> treeMap) {
Comparator<StockItem> valueComparator =
new Comparator<StockItem>() {
public int compare(StockItem o1, StockItem o2) {
int res = o1.Name.compareTo(o2.Name);
return res != 0 ? res : 1; // to preserve items with equal values
}
};
//THIS LINE THROWS AN ERROR:
TreeMap<String, StockItem> sortedByValues = new TreeMap<String, StockItem>(valueComparator);
sortedByValues.putAll(treeMap);
return sortedByValues;
}
}
The line:
TreeMap<String, StockItem> sortedByValues = new TreeMap<String, StockItem>(valueComparator);
gives this error:
error: no suitable constructor found for TreeMap(Comparator).
That makes sense but is there another way I can achieve my goal?
THIS IS NOT A DUPLICATE. My question is regarding using classes as values in the TreeMap AND sorting on objects of those classes. The "duplicate" only deals with Primitives as values