首页 > 代码库 > Map中按value值排序

Map中按value值排序

大家都知道,在java中的集合Map中按键值key排序比较简单,只需引用集合TreeMap即可,可是怎样实现按value值排序呢?下面我们来测试一下:

public class TestHashMap {
	public static void main(String[] args) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("zhangsan", 1);
		map.put("lisi", 2);
		map.put("wangwu", 0);
		
		List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {

			public int compare(Map.Entry<String,Integer> o1, Map.Entry<String,Integer> o2) {
				Integer one = o1.getValue();
				Integer two = o2.getValue();
				return two.compareTo(one);
			}
			
		});
		
		for(Map.Entry<String,Integer> entry : list)
			System.out.println(entry.getKey()+":"+entry.getValue());
	}
}

输出结果为:

lisi:2
zhangsan:1
wangwu:0


结果即是以value值从大到小进行排序的!