Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a hashmap by the Integer Value [duplicate]

Tags:

java

hashmap

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)

like image 466
GameDevGuru Avatar asked Jan 10 '14 21:01

GameDevGuru


2 Answers

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
like image 83
Evgeniy Dorofeev Avatar answered Oct 01 '22 19:10

Evgeniy Dorofeev


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;
    }
});
like image 24
Joseph Martin Avatar answered Oct 01 '22 19:10

Joseph Martin