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():
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.
Before sorting: Company Price Dell 32000 HP 20000 Lenovo 19990 Samsung 36546 Apple 65000 Asus 21478 Sorting values in ascending order: Company Price Lenovo 19990 HP 20000 Asus 21478 Dell 32000 Samsung 36546 MAC Book 65000 Sorting values in descending order: Company Price MAC Book 65000 Samsung 36546 Dell 32000 Asus 21478 HP 20000 Lenovo 19990
Next TopicJava Tutorial
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week