0

I am trying to sort a Hashmap, using a TreeMap, based on the values of keys and not the key itself. I am not able to understand how the code works. After referring to multiple sources on internet, I was able to get it to work. Here is what I have written:

    public void getSort(HashMap<String, Integer> map){ //map is to be sorted
            SortMap comparator = new SortMap(map); //What happens here?
            Map<String, Integer> new_map = new TreeMap<String, Integer>(comparator); //Passing comparator to TreeMap's constructor
            new_map.putAll(map); //and here ?
            System.out.println(new_map);
    }

my comparator class is this:

public class SortMap implements Comparator<Object> {

    Map<String, Integer> map;

    public SortMap(Map<String, Integer> map) {
        this.map = map;
    }

    public int compare(Object obj1, Object obj2) {

        if (map.get(obj2) == map.get(obj1))
            return 1;
        else
            return ((Integer) map.get(obj2)).compareTo((Integer)map.get(obj1));

    }
}

I do not understand the first 3 lines in getSort() func. I have not yet seen comparator being used like this before.

It has been only a month since i started java, so please do not be too harsh on me. I refered here for comparator and comparable: http://www.programcreek.com/2011/12/examples-to-demonstrate-comparable-vs-comparator-in-java/

darth
  • 169
  • 1
  • 16
  • 4
    Duplicate: http://stackoverflow.com/q/2864840/1743880 – Tunaki Sep 30 '15 at 22:09
  • No, in the question you linked, the compare function in op's comparator class is wrong. The best chosen answer does it in a completely different way. Iam asking help with my particular code. – darth Sep 30 '15 at 22:21
  • 1
    I think that you are being hasty in discounting the suggested duplicate. For one thing, it tells you why trying to sort a tree map based on its values is wrong. For another, it shows you how to implement a type-safe comparator, rather than relying on casts. – Andy Turner Sep 30 '15 at 23:05
  • 2
    By the way, you should be returning zero if the values are equal, since otherwise the comparison isn't antisymmetrical (it should be the case that `cmp.compare(obj1, obj2) > 0 <=> cmp.compare(obj2, obj1) < 0`). You can just remove the conditional, keeping the false branch. – Andy Turner Sep 30 '15 at 23:14
  • i did that to handle duplicates, i.e., if 2 or more keys have same value, then one of them is placed after the other. – darth Sep 30 '15 at 23:23
  • 2
    Yeah, but then you have an asymmetric relationship where `B > A` and `A > B`. Several collections will throw exceptions if they detect an inconsistent comparator. – chrylis -cautiouslyoptimistic- Sep 30 '15 at 23:35
  • ok then i will start again. Point me to some resource relating to this concept or ques.Thanks everyone. – darth Sep 30 '15 at 23:48

0 Answers0