How to sort a hashmap
by the integer value and one of the answers that I found is here
that written by Evgeniy Dorofeev and his answer was like this
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Object[] a = map.entrySet().toArray();
Arrays.sort(a, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Map.Entry<String, Integer>) o2).getValue().compareTo(
((Map.Entry<String, Integer>) o1).getValue());
}
});
for (Object e : a) {
System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
+ ((Map.Entry<String, Integer>) e).getValue());
}
output
c : 6
a : 4
b : 2
my question is how the sort become Desc ?? and if I want to sort the HashMap
Asc How can I do that ??
and the last question is : How can I have the first element after sorting?