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/
