4.8 Java HashMap常用方法

当需要计数器的时候,HashMap非常有用。

HashMap countMap = new HashMap();
 
//.... 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 map = new HashMap();
for (Map.Entry 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 {
 
    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);

你可能感兴趣的:(4.8 Java HashMap常用方法)