Java中HashMap排序和遍曆

來源:互聯網
上載者:User

HashMap排序

1、按照key排序

對於java中Map的排序,有排序Map,比如TreeMap,對於這個Map,首先只能按照鍵排序,其次再put和remove的時候由於需要排序,效能上會有所犧牲。

這種方案,使用hashmap進行建立和添加,如果需要按照key排序,則可以將該hashmap作為參數傳遞到new TreeMap(hashmap),則可以完成按照key的排序:

TreeMap treemap = new TreeMap(hashmap);  

TreeMap treemap = new TreeMap(hashmap);

 

2、按照value排序

使用hashmap,然後添加比較子,進行排序

   Map<String, Integer> keyfreqs = new HashMap<String, Integer>();   

   ArrayList<Entry<String,Integer>> l = new ArrayList<Entry<String,Integer>>(keyfreqs.entrySet());     

   Collections.sort(l, new Comparator<Map.Entry<String, Integer>>() {     

  
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {     

               
return (o2.getValue() - o1.getValue());     }     });   

  

   for(Entry<String,Integer> e : l) {   

       System.out.println(e.getKey() + "::::" + e.getValue());   

      }  

 

HashMap遍曆

在java中使用HashMap是主要有兩種遍曆方法,代碼如下:

第一種:

HashMap hashmap = new HashMap();

Iterator iterator = hashmap.keySet().iterator();

while (iterator.hasNext()) {

     Object value = hashmap.get(iterator.next());

}

 

第二種:

HashMap hashmap = new HashMap();

Iterator iterator = hashmap.entrySet().iterator();           

while (iterator .hasNext()) {

    Entry entry = (Entry) iterator .next();

    Object value= entry.getValue();

    Object key =entry.getKey();

   }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.