Javatpoint Logo
Javatpoint Logo

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	
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




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA