How to Sort HashMap by ValueIn 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() methodJava collections class provides a method to sort all list implementations such as LinkedList and ArrayList. There are two overloaded sort methods():
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 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 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India