-1

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


Mike6679
  • 5,547
  • 19
  • 63
  • 108
  • 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 – Mike6679 Feb 18 '15 at 06:15
  • 1
    This *is* a duplicate. You cannot use primitives as values in a generically-typed class in Java. You can only use objects. The duplicated question refers to objects of type Double (which can be auto-boxed from primitive `double`s) so the answers there can be applied to your question. – Cameron Skinner Feb 18 '15 at 07:09

1 Answers1

1

The constructor for TreeMap that takes a Comparator is TreeMap(Comparator<? super K> comparator).

In other words, a TreeMap will only sort based on the keys, not the values (which is what your example is attempting).

Edit: more complete answer - Java TreeMap Comparator

Community
  • 1
  • 1
spudone
  • 1,267
  • 7
  • 10