Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a hashmap by the Integer Value desc

Tags:

java

sorting

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?

like image 424
Abeer zaroor Avatar asked Dec 20 '15 13:12

Abeer zaroor


2 Answers

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()));
like image 179
luk2302 Avatar answered Oct 13 '22 01:10

luk2302


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.
like image 30
SMA Avatar answered Oct 12 '22 23:10

SMA