1. 程式人生 > >HashMap遍歷與按key排序。

HashMap遍歷與按key排序。

Google搜尋 hashmap 遍歷 寫道
第一種: 
Map map = new HashMap(); 
Iterator iter = map.entrySet().iterator(); 
while (iter.hasNext()) { 
    Map.Entry entry = (Map.Entry) iter.next(); 
    Object key = entry.getKey(); 
    Object val = entry.getValue(); 

效率高,以後一定要使用此種方式! 
第二種: 
Map map = new HashMap(); 
Iterator iter = map.keySet().iterator(); 
while (iter.hasNext()) { 
    Object key = iter.next(); 
    Object val = map.get(key); 

效率低,以後儘量少使用! 

關於hashmap 按value排序

  最近開發中用到了HashMap ,而且想到要利用其value的大小排序。。真是個傷腦筋的問題。 還好,經過查閱各個地方的資料。發現這個下邊的程式碼處理是最簡單有效的。程式碼很少,卻達到目的了。 一般我堅持的一個原則的是:能簡單處理的,儘量不做複雜工作。 關鍵程式碼部分如下: HashMap map_Data=new HashMap();
    map_Data.put("A", "98");
    map_Data.put("B", "50");
    map_Data.put("C", "50");
    map_Data.put("D", "25");
    map_Data.put("E", "85");
    System.out.println(map_Data);
    List<Map.Entry<String, String>> list_Data = new ArrayList<Map.Entry<String, String>>(map_Data.entrySet());     Collections.sort(list_Data, new Comparator<Map.Entry<String, String>>()
      {  
          public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
          {
           if(o2.getValue()!=null&&o1.getValue()!=null&&o2.getValue().compareTo(o1.getValue())>0){
            return 1;
           }else{
            return -1;
           }
             
          }
      });
    System.out.println(list_Data); 主要的一個知識點在這個Collections.sort(list,Comparator介面實現)地方,而最最重要核心部分是這個Comparator實現。因為Comparator實現決定你的排序。採用了隱藏類實現方式。