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