在Java中,我们可以使用TreeMap该类通过其键对地图进行排序。该类非常易于使用。但是,有时我们需要按其值对map进行排序。如何通过其值对映射进行排序是Java程序员最常问的问题。在本文中,我将开发编写这种方法的最佳方法。
1.天真的方法
以下是对<String,Integer>对的映射进行排序的解决方案。这通常用于计数单词的频率。
import java.util.Comparator;import java.util.HashMap;import java.util.TreeMap;
public class SortMapByValue {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 10);
map.put("b", 30);
map.put("c", 50);
map.put("d", 40);
map.put("e", 20);
System.out.println(map);
TreeMap<String, Integer> sortedMap = sortMapByValue(map);
System.out.println(sortedMap);
}
public static TreeMap<String, Integer> sortMapByValue(HashMap<String, Integer> map){
Comparator<String> comparator = new ValueComparator(map);
//TreeMap is a map sorted by its keys.
//The comparator is used to sort the Tr