How can I sort a Map Key, Value by Values in Java?
To sort a Map Key, Value by values, you can convert it to a List of entries and then use Collections. Sort with a custom comparator that compares the values. Example:
Map<String, Integer> map = new HashMap
map. Put (“a”, 3)
map. Put (“b”, 1)
map. Put (“c”, 2)
List<Map. Entry<String, Integer>> list = new Array List<>(map.entrySet
In Java, you can sort a Map by its values using the following approaches:
- Using Java 8 Stream API
- import java.util.HashMap;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.stream.Collectors;
public class Main – public static void main (String args {Map<String, Integer> map = new HashMap<>
map.put(“John”, 25)
map.put(“Alice”, 30)
map.put(“Bob”, 20)
- LinkedHashMap::new
- System.out.println(sortedMap)
- Using Comparator and TreeMap
- import java.util.Comparator;
- import java.util.Map;
- import java.util.TreeMap;