SortKeyMap.java package study.base.map; import java.util.Comparator;import java.util.Map;import java.util.TreeMap; public class SortKeyMap { public static void main(String[] args) { SortKeyMap sortMap=new SortKeyMap(); Map map = new TreeMap
package study.base.map; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; public class SortKeyMap { public static void main(String[] args) { SortKeyMap sortMap=new SortKeyMap(); Mapmap = new TreeMap (); map.put("KFC",123456); map.put("WNBA", 4566); map.put("NBA", 333); map.put("CBA", 44444); Map resultMap = sortMap.sortMapByValue(map); //按Value进行排序 for (Map.Entry entry : resultMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } /** * 使用 Map按value进行排序 * @param map * @return */ public Map sortMapByValue(Map map) { if (map == null || map.isEmpty()) { return null; } Map sortMap = new TreeMap (new MapComparator()); sortMap.putAll(map); return sortMap; } //比较器类 class MapComparator implements Comparator { public int compare(String me1, String me2) { return me1.compareTo(me2); } } }