Java HashMap中的常用API
HashMap is very useful when a counter is required.1
2
3
4
5
6
7
8HashMap<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);
}
loop through hashmap
1 | Iterator it = mp.entrySet().iterator(); |
2 print hashmap
1 | public static void printMap(Map mp) { |
3 sort hashmap by value
The following code example take advantage of a constructor of TreeMap here.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class 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
}
}1
2
3
4
5
6
7
8
9
10
11HashMap<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);
There are different ways of sorting HashMap, this way has been voted the most in stackoverflow