- Store中的數據爲
Map<String, Integer>
- 不要臨時抱佛腳兩種數據類型轉換爲一個字符串。
- 拿到項設置成一個列表,並對其進行排序
- 把分類項設置成一個有序圖
下面是一些代碼,將做到這一點:
public static void main(String[] args) {
// Set up and load the map
Map<String, Integer> nameAgeMap = new HashMap<String, Integer>();
nameAgeMap.put("katy", 1);
nameAgeMap.put("chris", 44);
nameAgeMap.put("alice", 11);
nameAgeMap.put("josiah", 22);
nameAgeMap.put("john", 2);
// Create-and-load a List of entries
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(nameAgeMap.entrySet());
// Sort the list using a custom Comparator that compares the ages
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}});
// Load the entries into a Map that preserves insert order
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : entries)
sortedMap.put(entry.getKey(), entry.getValue());
// All done - let's see what we got
System.out.println(sortedMap);
}
輸出:
{katy=1, john=2, alice=11, josiah=22, chris=44}
爲什麼這麼複雜? Integer類完全能夠執行自己的比較 – 2011-12-15 10:30:06
@JohanSjöberg是的,你是對的。其實我不知道這個感謝清除概念 – Pratik 2011-12-15 10:34:35