java hashmap 常用方法_Java的HashMap中的常用方法总结
HashMap在編程中是一個非常有用的工具,使用的頻率很高,所以本文簡單總結(jié)一下hashmap的常用方法
遍歷HashMap
可以通過entryset取得iter,然后逐個遍歷
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
也可以直接簡單的for循環(huán)遍歷
Map map = new HashMap();
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " +
entry.getValue());
}
打印HashMap
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
根據(jù)HashMap的value進行排序
class ValueComparator implements Comparator {
Map base;
public ValueComparator(Map base) {
this.base = base;
}
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
HashMap countMap = new HashMap();
//add a lot of entries
countMap.put("a", 10);
countMap.put("b", 20);
ValueComparator vc = new ValueComparator(countMap);
TreeMap sortedMap = new TreeMap(vc);
sortedMap.putAll(countMap);
printMap(sortedMap);
這種方法是在stackoverflow上被voted最多的,借用treeMap的構(gòu)造函數(shù)
總結(jié)
以上是生活随笔為你收集整理的java hashmap 常用方法_Java的HashMap中的常用方法总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mooc作业怎么上传附件_交作业的一二三
- 下一篇: 判断是否是数字类型php_PHP函数补完