对Map中数据,按value值排序方法

1 Map<String,Integer>>类型


//声明
Map<String,Integer> hashMap = new HashMap<String,Integer>();
//向Map中添加数据
//.....
//转换
ArrayList<Entry<String, Integer>> arrayList = new ArrayList<Entry<String, Integer>>(
hashMap.entrySet());
//排序
Collections.sort(arrayList, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> map1,
Map.Entry<String, Integer> map2) {
return (map2.getValue() - map1.getValue());
}
});
//输出
for (Entry<String, Integer> entry : arrayList) {
System.out.println(entry.getKey() + "\t" + entry.getValue());
}

2 Map<String,Float>类型


                //声明
		Map hashMap = new HashMap();
		//向Map中添加数据
		//.....
		//转换
		ArrayList> arrayList = new ArrayList>(hashMap.entrySet());
		//排序
		Collections.sort(arrayList, new Comparator>(){
			public int compare(Map.Entry map1,
					Map.Entry map2) {
				return ((map2.getValue() - map1.getValue() == 0) ? 0
						: (map2.getValue() - map1.getValue() > 0) ? 1
								: -1);
			}
		});
		//输出
		for (Entry entry : arrayList) {
			System.out.println(entry.getKey() + "\t" + entry.getValue());
		}

3 Map<String,Double>类型


                //声明
		Map hashMap = new HashMap();
		//向Map中添加数据
		//.....
		//转换
		ArrayList> arrayList = new ArrayList>(hashMap.entrySet());
		//排序
		Collections.sort(arrayList, new Comparator>(){
			public int compare(Map.Entry map1,
					Map.Entry map2) {
				return ((map2.getValue() - map1.getValue() == 0) ? 0
						: (map2.getValue() - map1.getValue() > 0) ? 1
								: -1);
			}
		});
		//输出
		for (Entry entry : arrayList) {
			System.out.println(entry.getKey() + "\t" + entry.getValue());
		}  

posted on 2014-04-09 21:02  Letters_Zhang  阅读(761)  评论(0)    收藏  举报

导航