Java HashMap 中常用方法
原文地址:http://www.programcreek.com/2009/02/a-simple-treeset-example/
当需要计数器时,HashMap 非常有用。
HashMap<String, Integer> countMap = new HashMap<String, Integer>();
//.... a lot of a's like the following
if(countMap.keySet().contains(a)){
countMap.put(a, countMap.get(a)+1);
}else{
countMap.put(a, 1);
}
1. 循环遍历 HashMap
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
2. 打印 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
}
}
3. 按值排序 HashMap
下面的示例代码利用了一个 TreeMap 的构造函数。
class ValueComparator implements Comparator<String> {
Map<String, Integer> base;
public ValueComparator(Map<String, Integer> 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<String, Integer> countMap = new HashMap<String, Integer>();
//add a lot of entries
countMap.put("a", 10);
countMap.put("b", 20);
ValueComparator vc = new ValueComparator(countMap);
TreeMap<String,Integer> sortedMap = new TreeMap<String,Integer>(vc);
sortedMap.putAll(countMap);
printMap(sortedMap);
有不同的方法来排序 HashMap,这种方式在 stackoverflow 中投票最多。