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) {
Map tmap = 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排序
Map resMap = sortMapByKey(tmap);

for (Map.Entry entry : resMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}

/**
* 让 Map按key进行排序
*/
public static Map sortMapByKey(Map map) {
if (map == null || map.isEmpty()) {
return null;
}
Map sortMap = 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