HashMap in java provides quick lookups. They store items in “key, value” pairs. To get a value from the HashMap, we use the key corresponding to that entry.
HashMaps are a good method for implementing Dictionaries and directories.
Key and Value can be of different types (eg - String, Integer).
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. To learn more about comparator, read this tutorial.
Once we have the list of values in a sorted manner, we build the HashMap again based on this new list.
Let’s look at the code.
We first get the String values in a list. Then we sort the list.
To sort the String values in the list we use a comparator. This comparator sorts the list of values alphabetically.
Once, we have sorted the list, we build the HashMap based on this sorted list.
The complete code is as follows :
Output :
HashMap entries are sorted according to String value.
If values in the HashMap are of type Integer, the code will be as follows :
Output :
Here HashMap values are sorted according to Integer values.
If you notice the above examples, the Value objects implement the Comparator interface. Let’s look at an example where our value is a custom object.
We can also create a custom comparator to sort the hash map according to values. This is useful when your value is a custom object.
Let’s take an example where value is a class called ‘Name’. This class has two parameters, firstName and lastName.
The code for class Name is :
The custom comparator will look like :
We are sorting the names according to firstName, we can also use lastName to sort. Rather than using a list to get values from the map, we’ll be using LinkedHashMap to create the sorted hashmap directly.
The complete code is :
Output :
This tutorial covered sorting of HashMap according to Value. Sorting for String values differs from Integer values. String values require a comparator for sorting. Whereas, Integer values are directly sorted using Collection.sort().
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.