Java Map按Key值进行排序

时间:2025-04-03 22:22:10

package ;

import ;
import ;
import ;

public class SortMapTest {

	public static void main(String[] args) {
		Map<String, String> tmap = new TreeMap<String, String>();
		("abc", "2");
		("ace", "3");
		("cef", "2");
		("Weight", "6");
		("BLue", "6");
		("BLUe", "6");
		
		//对map利用key排序
		Map<String, String> resMap = sortMapByKey(tmap);

		for (<String, String> entry : ()) {
			(() + " " + ());
		}
	}

	/**
	 * 让 Map按key进行排序
	 */
	public static Map<String, String> sortMapByKey(Map<String, String> map) {
		if (map == null || ()) {
			return null;
		}
		Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
		(map);
		return sortMap;
	}
}

//实现一个比较器类

class MapKeyComparator implements Comparator<String> {

	@Override
	public int compare(String s1, String s2) {
		return (s2);  //从小到大排序
	}
}
输出结果:

BLUe 6
BLue 6
Weight 6
abc 2
ace 3
cef 2

基咯咯 767696856