Java HashMap排序

HashMap排序可以分爲按鍵排序與按值排序兩種,實現思路是先轉爲List容器,再重寫比較函數,調用java內置排序算法即可。

示例代碼如下(使用時根據需要修改map容器類型):

        HashMap<String, Double> map = new HashMap<String, Double>();
		map.put("key1", Math.random() * 100);
		map.put("key4", Math.random() * 100);
		map.put("key3", Math.random() * 100);
		map.put("key5", Math.random() * 100);
		map.put("key2", Math.random() * 100);
		
		List<Map.Entry<String, Double>> mapList = 
				new ArrayList<Map.Entry<String, Double>>(map.entrySet()); 
		
//		排序前打印
		System.out.println("排序前");
		for (Map.Entry<String, Double> entry : mapList) {
			System.out.println(entry.toString());
		}
		System.out.println();

		Collections.sort(mapList, new Comparator<Map.Entry<String, Double>>() {
			public int compare(Map.Entry<String, Double> obj1, Map.Entry<String, Double> obj2) {
				// 請使用內置比較函數, 否則可能會報錯, 違反使用約定
				// 具體要滿足交換律, 即返回值compare(x, y)與compare(y, x)應一致
				return obj1.getValue().compareTo(obj2.getValue()); // 比較map值
//				return obj1.getKey().compareTo(obj2.getKey()); // 比較map鍵
			}
		});
		
//		排序後打印
		System.out.println("排序後");
		for (Map.Entry<String, Double> entry : mapList) {
			System.out.println(entry.toString());
		}
按值排序結果:

排序前
key1=40.189446938991416
key2=97.14547760681302
key5=39.86978413432413
key3=44.246717054280374
key4=65.19003398617575

排序後
key5=39.86978413432413
key1=40.189446938991416
key3=44.246717054280374
key4=65.19003398617575
key2=97.14547760681302


按鍵排序結果:

排序前
key1=71.17675919899192
key2=88.06383506265738
key5=17.37417655482928
key3=1.89149771013285
key4=72.09130459451002

排序後
key1=71.17675919899192
key2=88.06383506265738
key3=1.89149771013285
key4=72.09130459451002
key5=17.37417655482928


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