HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("a", 4);
map.put("c", 6);
map.put("b", 2);
Desired output(HashMap):
c : 6
a : 4
b : 2
I haven't been able to find anything about Descending the order by value.
How can this be achieved? (Extra class not preferred)
Try 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
You can't explicity sort the HashMap, but can sort the entries. Maybe something like this helps:
// not yet sorted
List<Integer> intList = new ArrayList<Integer>(map.values());
Collections.sort(intList, new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
// for descending order
return o2 - o1;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With