map排序
程序员文章站
2024-02-17 15:30:40
...
对map的key进行排序是蛮简单的,直接一个
HashMap map = new HashMap();
map.put("0201", "0201");
map.put("01", "01");
map.put("0304", "0304");
map.put("0101", "0101");
Object[] key = map.keySet().toArray();
Arrays.sort(key);
for (int i = 0; i < key.length; i++) {
System.out.println(map.get(key[i]));
}
就行了。
但对于value进行排序不能只是这么简单,得重写比较
Map hashMap = new HashMap();
List arrayList = new ArrayList(hashMap.entrySet());
Collections.sort(arrayList, new Comparator() {
public int compare(Object o1, Object o2) {
Map.Entry obj1 = (Map.Entry) o1;
Map.Entry obj2 = (Map.Entry) o2;
return (obj1.getKey()).toString().compareTo(obj2.getKey());
}
});
// 将HASHMAP中的数据排序-------------------------------------------
for (Iterator iter = arrayList.iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String)entry.getKey();
..........
}