package com.cute.test;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class SortMapTest {
public static void main(String[] args) {
Maptmap = new TreeMap ();
tmap.put("abc", "2");
tmap.put("ace", "3");
tmap.put("cef", "2");
tmap.put("Weight", "6");
tmap.put("BLue", "6");
tmap.put("BLUe", "6");
//对map利用key排序
MapresMap = sortMapByKey(tmap);
for (Map.Entryentry : resMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
/**
* 让 Map按key进行排序
*/
public static MapsortMapByKey(Map map) {
if (map == null || map.isEmpty()) {
return null;
}
MapsortMap = new TreeMap (new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
}
//实现一个比较器类
class MapKeyComparator implements Comparator{
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2); //从小到大排序
}
}
输出结果:
BLUe 6
BLue 6
Weight 6
abc 2
ace 3
cef 2