[java] Java TreeMap Comparator

I need a comparator for a TreeMap. Should I write this anonymously in the constructor for my TreeMap? How else could I write my comparator. Currently, Java does not like my code (can I do this anonymously?):

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<Entry<String, Double>>()
    {
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2)
        {
            return o1.getValue().compareTo(o2.getValue());
        } 
    });
  1. Can I do the above anonymously?
  2. How else could I do this?
  3. I want to sort myMap by the Value not the Key

This question is related to java comparator treemap sortedmap

The answer is


The comparator should be only for the key, not for the whole entry. It sorts the entries based on the keys.

You should change it to something as follows

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<String>()
    {
        public int compare(String o1, String o2)
        {
            return o1.compareTo(o2);
        } 
});

Update

You can do something as follows (create a list of entries in the map and sort the list base on value, but note this not going to sort the map itself) -

List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
    Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
        @Override
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());