I am trying to sort LinkedHashMap based on its values. What I dont understand are the results. Its seems to be taking only two keys for the sorting. Any pointers as to what am I missing?
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedHashMap<Integer, Integer> sorting = new LinkedHashMap<Integer, Integer>();
sorting.put(1, 100);
sorting.put(10, 100);
sorting.put(20, 200);
sorting.put(30, 100);
sorting.put(40, 100);
sorting.put(50, 200);
for (Entry<Integer, Integer> entry : sorting.entrySet()) {
Integer key = entry.getKey();
Integer value = entry.getValue();
System.out.println("LINKED UNSORTED === key: "+ key + '\t' + "Value: " + value);
// do stuff
}
Comparator<Integer> comparator = new ValueCom(sorting);
TreeMap<Integer, Integer> sortedMap =new TreeMap<Integer, Integer>(comparator);
sortedMap.putAll(sorting);
for (Entry<Integer, Integer> entry : sortedMap.entrySet()) {
Integer key = entry.getKey();
Integer value = entry.getValue();
System.out.println("SORTED === key: "+ key + '\t' + "Value: " + value);
// do stuff
}
}
}
class ValueCom implements Comparator<Integer> {
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
public ValueCom(HashMap<Integer, Integer> map) {
this.map.putAll(map);
}
public int compare(Integer keyA, Integer keyB){
return map.get(keyB).compareTo(map.get(keyA));
}
}
The current output is as explained above
LINKED UNSORTED === key: 1 Value: 100
LINKED UNSORTED === key: 10 Value: 100
LINKED UNSORTED === key: 20 Value: 200
LINKED UNSORTED === key: 30 Value: 100
LINKED UNSORTED === key: 40 Value: 100
LINKED UNSORTED === key: 50 Value: 200
SORTED === key: 20 Value: 200
SORTED === key: 1 Value: 100
In TreeMap
the uniqueness of keys is determined by the passed Comparator
. Since your Comparator
compares values of the original Map
, all the entries having the same value are considered by the TreeMap
to have the same key, so only one entry is added to the TreeMap
for each unique value.
If you want a Map
sorted by values, you can use a LinkedHashMap
for your sorted Map
, and make sure that you put the entries in the Map
in the desired order.