幾個對一個Map的keys或者values進行排序的java例子. 注意:
如果你使用的是 Java 8, 參考這篇文章 – Java 8 – 怎樣對Map排序 1. 按照key排序
1.1 用 java.util.TreeMap, 它將自動根據keys對Map進行排序. SortByKeyExample1.java
package com.mkyong.test;import java.util.HashMap;import java.util.Map;import java.util.TreeMap;public class SortByKeyExample1 { public static void main(String[] args) { Map<String, String> unsortMap = new HashMap<String, String>(); unsortMap.put("Z", "z"); unsortMap.put("B", "b"); unsortMap.put("A", "a"); unsortMap.put("C", "c"); unsortMap.put("D", "d"); unsortMap.put("E", "e"); unsortMap.put("Y", "y"); unsortMap.put("N", "n"); unsortMap.put("J", "j"); unsortMap.put("M", "m"); unsortMap.put("F", "f"); System.out.println("Unsort Map......"); printMap(unsortMap); System.out.println("\nSorted Map......By Key"); Map<String, String> treeMap = new TreeMap<String, String>(unsortMap); printMap(treeMap); } //pretty print a map public static <K, V> void printMap(Map<K, V> map) { for (Map.Entry<K, V> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey()+ " Value : " + entry.getValue()); } }}
Output
Unsort Map......Key : A Value : aKey : B Value : bKey : C Value : cKey : D Value : dKey : E Value : eKey : F Value : fKey : Y Value : yKey : Z Value : zKey : J Value : jKey : M Value : mKey : N Value : nSorted Map......By KeyKey : A Value : aKey : B Value : bKey : C Value : cKey : D Value : dKey : E Value : eKey : F Value : fKey : J Value : jKey : M Value : mKey : N Value : nKey : Y Value : yKey : Z Value : z
1.2 另一個 java.util.TreeMap 例子 ,提供一個自訂的 Comparator 對可以進行降序排序. SortByKeyExample2.java
package com.mkyong.test;import java.util.Comparator;import java.util.HashMap;import java.util.Map;import java.util.TreeMap;public class SortByKeyExample2 { public static void main(String[] args) { Map<Integer, String> unsortMap = new HashMap<Integer, String>(); unsortMap.put(10, "z"); unsortMap.put(5, "b"); unsortMap.put(6, "a"); unsortMap.put(20, "c"); unsortMap.put(1, "d"); unsortMap.put(7, "e"); unsortMap.put(8, "y"); unsortMap.put(99, "n"); unsortMap.put(50, "j"); unsortMap.put(2, "m"); unsortMap.put(9, "f"); System.out.println("Unsort Map......"); printMap(unsortMap); System.out.println("\nSorted Map......By Key"); Map<Integer, String> treeMap = new TreeMap<Integer, String>( new Comparator<Integer>(