map sort

来源:互联网 发布:linux删除空文件夹 编辑:程序博客网 时间:2024/05/02 00:46

转自:http://blog.csdn.net/teedry/article/details/4844924


 map中的key,value排序

  如何对map进行排序呢?这就分别对map的key及value来排序。

map内部是按照hash算法存储的,有些输出的情况需要对于Map类进行排序。

 

[java] view plaincopy
  1. /** 
  2.      * @param h 
  3.      * @return 
  4.      * 实现对map按照value升序排序 
  5.      */  
  6.     @SuppressWarnings("unchecked")  
  7.     public static Map.Entry[] getSortedHashtableByValue(Map h) {  
  8.         Set set = h.entrySet();  
  9.         Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set  
  10.                 .size()]);  
  11.         Arrays.sort(entries, new Comparator() {  
  12.             public int compare(Object arg0, Object arg1) {  
  13.                 Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());  
  14.                 Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());  
  15.                 return key1.compareTo(key2);  
  16.             }  
  17.         });  
  18.   
  19.         return entries;  
  20.     }  
  21.   
  22.  /** 
  23.      * @param h 
  24.      * @return 
  25.      * 实现对map按照key排序 
  26.      */  
  27.     @SuppressWarnings("unchecked")  
  28.     public static Map.Entry[] getSortedHashtableByKey(Map h) {  
  29.   
  30.         Set set = h.entrySet();  
  31.   
  32.         Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set  
  33.                 .size()]);  
  34.   
  35.         Arrays.sort(entries, new Comparator() {  
  36.             public int compare(Object arg0, Object arg1) {  
  37.                 Object key1 = ((Map.Entry) arg0).getKey();  
  38.                 Object key2 = ((Map.Entry) arg1).getKey();  
  39.                 return ((Comparable) key1).compareTo(key2);  
  40.             }  
  41.   
  42.         });  
  43.   
  44.         return entries;  
  45.     }  


0 0
原创粉丝点击