Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort the elements of an HashMap according to their values? [duplicate]

I have the following HashMap:

HashMap<String, Integer> counts = new HashMap<String, Integer>();

What is the simplest way to order it according to the values?

like image 953
Anasaw Avatar asked Oct 16 '12 16:10

Anasaw


People also ask

Can you sort a HashMap based on values?

We can sort the entries in a HashMap according to keys as well as values. In this tutorial we will sort the HashMap according to value. The basic strategy is to get the values from the HashMap in a list and sort the list. Here if the data type of Value is String, then we sort the list using a comparator.

Does HashMap accept duplicates?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

How do you sort values in descending order in HashMap on the basis of key?

In order to sort in decreasing order, just reverse the order of Comparator using Collections. reverseOrder() or Comparator.


1 Answers

You can't sort a Map by the values, especially not a HashMap, which can't be sorted at all.

Instead, you can sort the entries:

List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
  public int compare(
      Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
    return entry1.getValue().compareTo(entry2.getValue());
  }
});

will sort the entries in ascending order of count.

like image 72
Louis Wasserman Avatar answered Nov 05 '22 06:11

Louis Wasserman