Abdul D.
—I don’t know how to sort a Map<Key, Value>
by its values in Java.
There are two ways to sort a map by its values in Java:
List<Map.Entry<K, V>>
to create a list of its entries, then use Collections.sort()
to sort that list based on the values of each entry.Stream
API to organize the map entries by value in a LinkedHashMap
.Consider the following map as an example:
Map<String, Integer> map = new HashMap<>(); map.put("Apple", 3); map.put("Banana", 1); map.put("Kiwi", 4); map.put("Cherry", 2);
The Banana
entry has the lowest value and would appear first in a sorted list.
List<Map.Entry<K, V>>
and Collections.sort()
You can convert the map’s entry set into a list and use Collections.sort()
to sort it based on the values.
import java.util.*; public class Main { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("Apple", 3); map.put("Banana", 1); map.put("Kiwi", 4); map.put("Cherry", 2); List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); list.sort(Map.Entry.comparingByValue()); for (Map.Entry<String, Integer> entry : list) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } } }
This creates a list from the map entries, uses sort()
with Map.Entry.comparingByValue()
to sort the list by values, and returns the following output:
Banana -> 1 Cherry -> 2 Apple -> 3 Kiwi -> 4
Stream
API (Java 8+)If you are using Java version 8 or later, you can use the Stream
API to sort the map by its values and collect the results into a LinkedHashMap
to preserve the order of the sorted entries.
import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("Apple", 3); map.put("Banana", 1); map.put("Kiwi", 4); map.put("Cherry", 2); Map<String, Integer> sortedMap = map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, // Merge function LinkedHashMap::new)); sortedMap.forEach((key, value) -> System.out.println(key + " -> " + value)); } }
Running this outputs:
Banana -> 1 Cherry -> 2 Apple -> 3 Kiwi -> 4
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.