所以必需自行撰寫,範例參考如下
import java.util.Collection;import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; public class sortMap { public static void main(String[] args){ Map<String, Integer> sortMap = new TreeMap<String, Integer>(); sortMap.put("N1", 5); sortMap.put("N2", 3); sortMap.put("N3", 1); sortMap.put("N4", 2); sortMap.put("N5", 4); Collection<Integer> sortMapTmp = sortMap.values(); System.out.println("--unsort Map--"); printSortMap(sortMap); sortMap = sortMapByComparator(sortMap); System.out.println("--sorted Map--"); printSortMap(sortMap); } private static Map<String, Integer> sortMapByComparator(Map<String, Integer> unsortMap){ List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet()); // Sorting the list based on values Collections.sort(list, new Comparator<Entry<String, Integer>>() { public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { //若要由小排到大 //如果 o1 > o2 => 回傳 1 // o1 = o2 => 回傳 0 // o1 < o2 => 回傳 -1 return o1.getValue().compareTo(o2.getValue()); } }); Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } private static void printSortMap(Map<String, Integer> sortMap){ for(Entry<String, Integer> entry : sortMap.entrySet()){ System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue()); } } }
[Reference]
http://stackoverflow.com/questions/1448369/how-to-sort-a-treemap-based-on-its-values
沒有留言:
張貼留言