How to Sort HashMap by Value
In Java, sorting HashMap by values is complicated because there is no direct method available. If we need to sort the HashMap by values, we should create a Comparator. It compares two elements based on the values.
After that get the Set of elements from the Map and convert Set into the List. Use the Collections.sort(List) method to sort the list of elements by values by passing customized comparator. Now create a new LinkedHashMap and copy the sorted elements into that. Since LinkedHashMap guarantees the insertion order of mappings. We get a HashMap whose values are in sorted order.
Java Collections.sort() method
Java collections class provides a method to sort all list implementations such as LinkedList and ArrayList. There are two overloaded sort methods():
- sort(List list): It sorts the elements of the List in ascending order of their natural order.
- sort(List list, Comparator <T>): It sorts the elements of the list according to the order included by the comparator.
Syntax
The method does not return any value. It throws the following exceptions:
ClassCastException: If the list contains elements that are not mutually comparable.
UnsupportedOperationException: If the specified list’s list-iterator does not support the set operation.
The difference between sorting HashMap by Keys and Values is that it can have duplicate values but not duplicate Keys. We cannot use TreeMap to sort values because TreeMap sorts elements by Keys.
Example of sort HashMap by Value
In the following example, we have sorted the map in ascending and descending order.
Output:
Before sorting: Company Price Dell32000 HP20000 Lenovo19990 Samsung36546 Apple65000 Asus21478 Sorting values in ascending order: Company Price Lenovo19990 HP20000 Asus21478 Dell32000 Samsung36546 MAC Book65000 Sorting values in descending order: Company Price MAC Book65000 Samsung36546 Dell32000 Asus21478 HP20000 Lenovo19990