现在的位置: 首页 > 综合 > 正文

Java中HashMap排序和遍历

2012年07月29日 ⁄ 综合 ⁄ 共 1244字 ⁄ 字号 评论关闭

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();

   }

抱歉!评论已关闭.