Sort hashmap by value in Java
In this post, you will learn how to sort the hashmap by value in the Java programming language.
Java Hashmap
Java HashMap class implements the Map interface, which allows us to store key and value pairs where keys should be unique. HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the null elements as well, but there should be only one null key. The HashMap is non synchronised and not thread safe. For non-threaded applications, HashMap should be preferred over Hashtable.
Java program to sort HashMap by value
To sort a HashMap by values, we need to create a Comparator. It compares two elements based on their values.
Java Collections.sort() method
Java collections class provides Collections.sort(List) method to sort the linked list, array, queue, and other data structures. In this post, we use this method to sort the list of elements by values by passing a customized comparator. It sorts the list elements by comparing the ASCII values of the elements. It has two overloaded sort methods.
- sort(List list) : It sorts the elements of the List in ascending order, the natural ordering of its element.
- sort(List list, Comparator <T>) : It sorts the elements of the list according to the order included by the comparator.
In the given Java program, we have sorted the hashmap in ascending order.
// Import the HashMap class
import java.util.*;
import java.util.Map.Entry;
public class Main {
public static void main(String[] args) {
// Create a HashMap object called fruit
LinkedHashMap<String, Integer> fruit = new LinkedHashMap<String, Integer>();
// Add keys and values (Fruit, Rate)
fruit.put("Kiwi", 220);
fruit.put("Guava", 80);
fruit.put("Orange", 130);
fruit.put("Apple", 100);
System.out.println("Original List: \n");
for (String i : fruit.keySet()) {
System.out.println("key: " + i + ", value: " + fruit.get(i));
}
System.out.println("\nSorted List by value: \n");
// calling the sortHashMap() method to sort the map
Map<String, String> result = sortHashMap(fruit);
for (Map.Entry entry : result.entrySet()) {
System.out.print("Key: " + entry.getKey()+", ");
System.out.println(" Value: " + entry.getValue());
}
}
public static LinkedHashMap sortHashMap(LinkedHashMap map) {
List <Entry<String, Integer>> capitalList = new LinkedList<>(map.entrySet());
// calling the sort() method of Collections
Collections.sort(capitalList, (l1, l2) -> l1.getValue().compareTo(l2.getValue()));
// create a new map
LinkedHashMap<String, Integer> result = new LinkedHashMap();
// get entry from list to the map
for (Map.Entry<String, Integer> entry : capitalList) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}
Output of the above code:
Original List:
key: Kiwi, value: 220
key: Guava, value: 80
key: Orange, value: 130
key: Apple, value: 100
Sorted List by value:
Key: Guava, Value: 80
Key: Apple, Value: 100
Key: Orange, Value: 130
Key: Kiwi, Value: 220
Related Articles
Java string split multiple delimitersEnum with values in Java
Convert array to list in Java
Java random number between 1 and 100
Calculating percentage in Java
Multiplication table program in Java
Java dialogue box
Fibonacci series using recursion in Java
Java sum of array
Circular prime in Java
Vowel and Consonant program in Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Java program to check leap year
Java program to find factorial of a number