首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java中HashMap排序跟遍历

2012-09-06 
Java中HashMap排序和遍历 .TreeMap treemap new TreeMap(hashmap)? 2、按照value排序使用hashmap,然后添

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

?? }

热点排行