Write a Java program that sorts the entries of a HashMap based on their values. Initialize a HashMap with string keys and integer values. Sort the entries based on values in ascending order and print the sorted entries.
Approach 1
importjava.util.*;publicclassMain {publicstaticvoidmain(String[] args) {// Initialize a HashMap with string keys and integer valuesHashMap<String,Integer> hashMap =newHashMap<>();hashMap.put("A",11);hashMap.put("B",10);hashMap.put("C",9);// Sort the entries based on values in ascending orderList<Map.Entry<String,Integer>> entryList =newArrayList<>(hashMap.entrySet());entryList.sort(Map.Entry.comparingByValue());// Print the sorted entriesSystem.out.println("Sorted Entries:");for (Map.Entry<String,Integer> entry : entryList) {System.out.println(entry.getKey() +": "+entry.getValue()); } }}
This program initializes a HashMap with string keys and integer values, then sorts the entries based on their values in ascending order using the Collections.sort() method with a custom comparator. Finally, it prints the sorted entries.
Approach 2
importjava.util.*;publicclassMain {publicstaticvoidmain(String[] args) {// Initialize a HashMap with string keys and integer valuesHashMap<String,Integer> hashMap =newHashMap<>();hashMap.put("A",11);hashMap.put("B",10);hashMap.put("C",9);// Create a TreeMap to sort entries by valuesTreeMap<Integer,String> sortedMap =newTreeMap<>();// Populate the TreeMap with values as keys and corresponding keys as valuesfor (Map.Entry<String,Integer> entry :hashMap.entrySet()) {sortedMap.put(entry.getValue(),entry.getKey()); }// Print the sorted entriesSystem.out.println("Sorted Entries:");for (Map.Entry<Integer,String> entry :sortedMap.entrySet()) {System.out.println(entry.getValue() +": "+entry.getKey()); } }}
In this approach, a TreeMap is used to sort the entries based on their values (now keys in the TreeMap). The values in the original HashMap become keys in the TreeMap, and the corresponding keys in the original HashMap become values in the TreeMap. This allows TreeMap's natural ordering to sort the entries based on their values. Finally, it prints the sorted entries.
Approach 3
importjava.util.*;publicclassMain {publicstaticvoidmain(String[] args) {// Initialize a HashMap with string keys and integer valuesHashMap<String,Integer> hashMap =newHashMap<>();hashMap.put("A",11);hashMap.put("B",10);hashMap.put("C",9);// Sort the entries based on values using streamsLinkedHashMap<String,Integer> sortedMap =newLinkedHashMap<>();hashMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEachOrdered(entry ->sortedMap.put(entry.getKey(),entry.getValue()));// Print the sorted entriesSystem.out.println("Sorted Entries:");sortedMap.forEach((key, value) ->System.out.println(key +": "+ value)); }}
In this approach, we use streams to sort the entries based on values. We first create a stream from the entry set of the HashMap, then use the sorted() method with a comparator that compares entries by their values. Finally, we collect the sorted entries into a LinkedHashMap, preserving the order of insertion, and print the sorted entries.
Approach 4
importjava.util.*;publicclassMain {publicstaticvoidmain(String[] args) {// Initialize a HashMap with string keys and integer valuesHashMap<String,Integer> hashMap =newHashMap<>();hashMap.put("A",11);hashMap.put("B",10);hashMap.put("C",9);// Convert HashMap entries to a listList<Map.Entry<String,Integer>> entryList =newArrayList<>(hashMap.entrySet());// Sort the list based on valuesCollections.sort(entryList,newComparator<Map.Entry<String,Integer>>() {publicintcompare(Map.Entry<String,Integer> entry1,Map.Entry<String,Integer> entry2) {returnentry1.getValue().compareTo(entry2.getValue()); } });// Create a new LinkedHashMap to preserve the insertion orderLinkedHashMap<String,Integer> sortedMap =newLinkedHashMap<>();for (Map.Entry<String,Integer> entry : entryList) {sortedMap.put(entry.getKey(),entry.getValue()); }// Print the sorted entriesSystem.out.println("Sorted Entries:");for (Map.Entry<String,Integer> entry :sortedMap.entrySet()) {System.out.println(entry.getKey() +": "+entry.getValue()); } }}
In this approach:
We use the entrySet() method to obtain a set of entries from the HashMap.
We use the stream() method to convert the set of entries into a stream of entries.
We use the sorted() method to sort the entries based on their values using the comparingByValue() method.
We use the forEachOrdered() method to insert the sorted entries into a new LinkedHashMap, preserving the order of insertion.
Finally, we print the sorted entries using the forEach() method and lambda expressions.
Approach 5
importjava.util.*;publicclassMain {publicstaticvoidmain(String[] args) {// Initialize a HashMap with string keys and integer valuesHashMap<String,Integer> hashMap =newHashMap<>();hashMap.put("A",11);hashMap.put("B",10);hashMap.put("C",9);// Sort the entries based on values using Java 8 streams and lambda expressionsLinkedHashMap<String,Integer> sortedMap =newLinkedHashMap<>();hashMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEachOrdered(entry ->sortedMap.put(entry.getKey(),entry.getValue()));// Print the sorted entriesSystem.out.println("Sorted Entries:");sortedMap.forEach((key, value) ->System.out.println(key +": "+ value)); }}
In this approach:
We use the entrySet() method to obtain a set of entries from the HashMap.
We use the stream() method to convert the set of entries into a stream of entries.
We use the sorted() method to sort the entries based on their values using the comparingByValue() method.
We use the forEachOrdered() method to insert the sorted entries into a new LinkedHashMap, preserving the order of insertion.
Finally, we print the sorted entries using the forEach() method and lambda expressions.
Approach 6
importjava.util.*;publicclassMain {publicstaticvoidmain(String[] args) {// Initialize a HashMap with string keys and integer valuesHashMap<String,Integer> hashMap =newHashMap<>();hashMap.put("A",11);hashMap.put("B",10);hashMap.put("C",9);// Create a TreeMap with a custom comparator to sort by valuesTreeMap<String,Integer> sortedMap =newTreeMap<>(newValueComparator(hashMap));// Put all entries from the HashMap to the TreeMapsortedMap.putAll(hashMap);// Print the sorted entriesSystem.out.println("Sorted Entries:");sortedMap.forEach((key, value) ->System.out.println(key +": "+ value)); }}// Custom comparator class to compare values in the HashMapclassValueComparatorimplementsComparator<String> {HashMap<String,Integer> map;publicValueComparator(HashMap<String,Integer> map) {this.map= map; } @Overridepublicintcompare(String key1,String key2) {Integer value1 =map.get(key1);Integer value2 =map.get(key2);// Compare values in descending orderreturnvalue1.compareTo(value2); }}
In this approach:
We create a custom ValueComparator class that implements the Comparator interface to compare values in the HashMap.
We create a TreeMap and pass an instance of the ValueComparator class to its constructor. This TreeMap will sort entries based on values.
We put all entries from the HashMap to the TreeMap using the putAll() method, which automatically sorts them based on the custom comparator.