I have a map
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(21,"A");
map.put(9,"B");
map.put(23,"C");
map.put(25,"D");
I sorted it like this
List<Integer> list = new LinkedList(map.keySet());
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1%10 - o2%10;
}
});
Map sortedMap = new LinkedHashMap();
for(Integer key: list){
sortedMap.put(key, map.get(key));
}
System.out.println(sortedMap);
Gives output {21=A, 23=C, 25=D, 9=B}
Even tried like this
Collections.sort(list);
Set set = map.entrySet();
Map result = new LinkedHashMap();
for (Iterator it = set.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
System.out.println(result.toString());
Still same result
Why 9 is coming at last it must the first entry .
% 10, you only keep the last digit of your numbers for the sort. :)