- 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