How to sort a Map<Key, Value> by values in Java
To sort a Map<Key, Value>
by values in Java, you can create a custom comparator that compares the values and pass it to the sort()
method of the Map.Entry
class. Here's an example using a lambda expression:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 3);
map.put("key2", 1);
map.put("key3", 2);
List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort((a, b) -> a.getValue().compareTo(b.getValue()));
for (Map.Entry<String, Integer> entry : entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
This will output the key-value pairs in ascending order of the values:
key2: 1 key3: 2 key1: 3
You can also use a method reference instead of a lambda expression:
List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort(Map.Entry.comparingByValue());
Note that this will only sort the entries in the list, not the original map. If you want to sort the original map, you will need to create a new sorted map using the sorted entries. Here's an example using the LinkedHashMap
class to preserve the order of the entries:
Map<String, Integer> sortedMap = new LinkedHashMap<>();
for (Map.Entry<String, Integer> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}