如何对map进行排序呢?这就分别对map的key及value来排序。 map内部是按照hash算法存储的,有些输出的情况需要对于Map类进行排序。 /** * @param h * @return * 实现对map按照value升序排序 */ @SuppressWarnings("unchecked") public static Map.Entry[] getSortedHashtableByValue(Map h) { Set set = h.entrySet(); Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set .size()]); Arrays.sort(entries, new Comparator() { public int compare(Object arg0, Object arg1) { Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString()); Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString()); return key1.compareTo(key2); } }); return entries; } /** * @param h * @return * 实现对map按照key排序 */ @SuppressWarnings("unchecked") public static Map.Entry[] getSortedHashtableByKey(Map h) { Set set = h.entrySet(); Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set .size()]); Arrays.sort(entries, new Comparator() { public int compare(Object arg0, Object arg1) { Object key1 = ((Map.Entry) arg0).getKey(); Object key2 = ((Map.Entry) arg1).getKey(); return ((Comparable) key1).compareTo(key2); } }); return entries; } 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/teedry/archive/2009/11/20/4844924.aspx
map中的key,value排序
最新推荐文章于 2024-05-13 21:32:22 发布