對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<String,Float> hashMap = new HashMap<String,Float>();
		//向Map中添加數據
		//.....
		//轉換
		ArrayList<Entry<String, Float>> arrayList = new ArrayList<Map.Entry<String,Float>>(hashMap.entrySet());
		//排序
		Collections.sort(arrayList, new Comparator<Map.Entry<String, Float>>(){
			public int compare(Map.Entry<String, Float> map1,
					Map.Entry<String,Float> map2) {
				return ((map2.getValue() - map1.getValue() == 0) ? 0
						: (map2.getValue() - map1.getValue() > 0) ? 1
								: -1);
			}
		});
		//輸出
		for (Entry<String, Float> entry : arrayList) {
			System.out.println(entry.getKey() + "\t" + entry.getValue());
		}

3.Map<String,Double>類型

		//聲明
		Map<String,Double> hashMap = new HashMap<String,Double>();
		//向Map中添加數據
		//.....
		//轉換
		ArrayList<Entry<String, Double>> arrayList = new ArrayList<Map.Entry<String,Double>>(hashMap.entrySet());
		//排序
		Collections.sort(arrayList, new Comparator<Map.Entry<String, Double>>(){
			public int compare(Map.Entry<String, Double> map1,
					Map.Entry<String,Double> map2) {
				return ((map2.getValue() - map1.getValue() == 0) ? 0
						: (map2.getValue() - map1.getValue() > 0) ? 1
								: -1);
			}
		});
		//輸出
		for (Entry<String, Double> entry : arrayList) {
			System.out.println(entry.getKey() + "\t" + entry.getValue());
		}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章