有如下一个 Map 对象:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(3,"A");
map.put(2,"B");
map.put(1,"C");
键值排序第一种方法:
Object[] key = map.keySet().toArray(); Arrays.sort(key); for(int i = 0; i<key.length; i++) { Log.i("sang", "value=>"+map.get(key[i])); }
键值排序第二种方法:
List arrayList = new ArrayList(map.entrySet()); Collections.sort(arrayList, new Comparator() { public int compare(Object arg1, Object arg2) { Map.Entry obj1 = (Map.Entry) arg1; Map.Entry obj2 = (Map.Entry) arg2; 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(); Log.i("sang","value =>"+map.get(key)); }