Sort Map by Value
Approach 1
import java.util.*;
public class Main {
public static void main(String[] args) {
// Initialize a HashMap with string keys and integer values
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("A", 11);
hashMap.put("B", 10);
hashMap.put("C", 9);
// Sort the entries based on values in ascending order
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(hashMap.entrySet());
entryList.sort(Map.Entry.comparingByValue());
// Print the sorted entries
System.out.println("Sorted Entries:");
for (Map.Entry<String, Integer> entry : entryList) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Approach 2
Approach 3
Approach 4
Approach 5
Approach 6
Last updated