Java program to sort a map by values
To sort a Map
by its values in Java, you can create a list of map entries and sort it using a custom Comparator
that compares values. Here's an example program that demonstrates how to do this:
import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class SortMapByValues { public static void main(String[] args) { // Create a HashMap with some key-value pairs Map<String, Integer> unsortedMap = new HashMap<>(); unsortedMap.put("Bob", 3); unsortedMap.put("Alice", 1); unsortedMap.put("Charlie", 2); // Create a list of map entries List<Map.Entry<String, Integer>> entryList = new ArrayList<>(unsortedMap.entrySet()); // Sort the list by values using a custom Comparator entryList.sort(Comparator.comparing(Map.Entry::getValue)); // Create a new LinkedHashMap to preserve the insertion order of the entries Map<String, Integer> sortedMap = new HashMap<>(); for (Map.Entry<String, Integer> entry : entryList) { sortedMap.put(entry.getKey(), entry.getValue()); } // Print the sorted map for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) { System.out.println(entry.getKey() + " => " + entry.getValue()); } } }
In this program, we first create a HashMap
called unsortedMap
with some key-value pairs. We then create a list of map entries called entryList
and initialize it with the entries of unsortedMap
.
Next, we sort the list of entries by values using a custom Comparator
that compares values. The Comparator.comparing
method is used to create a Comparator
that compares the values of each entry.
After sorting the list of entries, we create a new HashMap
called sortedMap
and insert each entry in the sorted order. Note that we use a HashMap
here instead of a TreeMap
because we want to preserve the insertion order of the entries.
Finally, we iterate through the sorted map using a for-each loop and print out each key-value pair. When you run this program, the output should be:
Alice => 1 Charlie => 2 Bob => 3