當需要對元素進行計數時,HashMap非常有用,如下例子,統計一個字符串中每個字符出現的次數:
package simplejava;
import java.util.HashMap;
import java.util.Map.Entry;
public class Q12 {
public static void main(String[] args) {
HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();
// .... a lot of a’s like the following
String chars = "abcabcabcghgk";
for(int i = 0; i < chars.length(); i++){
int a = chars.charAt(i);
if (countMap.keySet().contains(a)) {
countMap.put(a, countMap.get(a) + 1);
} else {
countMap.put(a, 1);
}
}
for(Entry<Integer, Integer> e : countMap.entrySet()){
System.out.println((char)(int)e.getKey() + " " + e.getValue());
}
}
}
輸出結果:
Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
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());
}
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
}
}
以下代碼往TreeMap的構造函數傳入一個比較器,來對map進行排序:
package simplejava;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.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
}
}
public class Q12 {
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
}
}
public static void main(String[] args) {
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中是最被推崇的;
注:使用了一個比較器Comparator對TreeMap排序,該比較器比較key的方式是取出key對應的value進行大小比較;
譯文地址:http://www.programcreek.com/2013/04/frequently-used-methods-of-java-hashmap/