7

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?

Community
  • 1
  • 1
Abeer zaroor
  • 320
  • 2
  • 17
  • 2
    you can probably reverse the order by switching `o2` with `o1` in the `compare` method - getting the first element is just `a[0]` and then use the same logic as in the for loop to get the value and the key!? – luk2302 Dec 20 '15 at 13:37
  • 1
    Possible duplicate of [How to sort a Map on the values in Java?](http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java) – Ramesh-X Dec 20 '15 at 13:50
  • no my question was about code that written by a user as I specified in my question :) – Abeer zaroor Dec 20 '15 at 14:00

3 Answers3

7

For inverse ordering switch o2 and o1. For getting the first element just access the array at index 0:

Map<String, Integer> map = new HashMap<>();
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>) o1).getValue().compareTo(
               ((Map.Entry<String, Integer>) o2).getValue());
    }
});
for (Object e : a) {
    System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : "
                     + ((Map.Entry<String, Integer>) e).getValue());
}        

System.out.println("first element is " + ((Map.Entry<String, Integer>) a[0]).getKey() + " : "
        + ((Map.Entry<String, Integer>) a[0]).getValue());        

Which prints

b : 2
a : 4
c : 6
first element is b : 2

If you have access to lambda expression you can simplify the sorting using those:

Arrays.sort(a, (o1, o2) -> 
   ((Map.Entry<String, Integer>) o1).getValue().compareTo(((Map.Entry<String, Integer>) o2).getValue()));
luk2302
  • 55,258
  • 23
  • 97
  • 137
3

In Java 8, you could do something like:

System.out.println(map.entrySet().stream().sorted((o1, o2) -> {
        return o2.getValue().compareTo(o1.getValue());
    }).findFirst());//would return entry boxed into optional which you can unbox.
SMA
  • 36,381
  • 8
  • 49
  • 73
2

First of all, answering your question: just reverse the result of compare method to change ASC to DESC.

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) {
        // just reverse the result of the comparison 
        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());
}

But if you need to work with a sorted Map, I suggest you use an instance of TreeMap that handles the sorting by itself.

Yury Fedorov
  • 14,508
  • 6
  • 50
  • 66