1. 程式人生 > 其它 >根據map的value進行排序2

根據map的value進行排序2

技術標籤:java演算法javahashmap

JAVA對Map按Value值排序

在java實際程式設計中經常需要使用到HashMap,TreeMap以及LinkedHashMap來儲存鍵值對,而java中對Map按Value排序並沒有已經寫好的方法,需要自己實現。
作者使用了自定義類以及Collections包的sort()方法實現Map的按值排序,具體程式碼如下:

  1. sortMap()
    輸入引數為需要排序的Map,輸出為LinkedHashMap型別,因為需要保證順序。
	public static LinkedHashMap<String, Integer> sortMap(Map<String, Integer> map){
		class MapClass{															//自定義類儲存鍵值對
			private String key;
			private int value;
			
			public MapClass(String key, int value) {
				super();
				this.key = key;
				this.value = value;
			}

			public String getKey() {
				return key;
			}

			public int getValue() {
				return value;
			}
			
			
		}
		class MapSortMethod implements Comparator<MapClass>{					//為自定義類實現排序方法
			@Override
			public int compare(MapClass o1, MapClass o2) {
				int result = Integer.compare(o1.getValue(), o2.getValue());		//按值大小升序排列
				//int result = Integer.compare(o2.getValue(), o1.getValue());	//按值大小降序排列	
				if(result != 0)
					return result;		
				return o1.getKey().compareTo(o2.getKey());						//值相同時按鍵字典順序排列
			}
		}
		
		ArrayList<MapClass> mapclass = new ArrayList<MapClass>();				//以ArrayList儲存自定義類
		for(String k: map.keySet())
			mapclass.add(new MapClass(k, map.get(k)));
		Collections.sort(mapclass, new MapSortMethod());						//使用Collections.sort()方法,第二個引數為自定義排序方法,需要實現Comparator介面
						
		LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		for(MapClass m: mapclass)
			sortedMap.put(m.getKey(), m.getValue());
		return sortedMap;														//用LinkedHashMap返回排好序的Map
	}
  1. 測試
	public static void main(String[] args) {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		map.put("math", 93);
		map.put("english", 88);
		map.put("chinese", 99);
		map.put("biology", 72);
		System.out.println(sortMap(map));
	}

輸出結果如下:
在這裡插入圖片描述
注:本文中使用到的依賴包如下:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;