当你要实现计数器的时候,HashMap是非常有用的。
1 2 3 4 5 6 7 8
| HashMap<String, Integer> countMap = new HashMap<String, Integer>(); if(countMap.keySet().contains(a)){ countMap.put(a, countMap.get(a)+1); }else{ countMap.put(a, 1); }
|
通过HashMap进行循环输出
1 2 3 4 5
| Iterator it = mp.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); System.out.println(pairs.getKey() + " = " + pairs.getValue()); }
|
1 2 3 4
| 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
1 2 3 4 5 6 7 8
| 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(); } }
|
3.根据HashMap 的值排序
最好的方式是使用TreeMap 来完成,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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; } } }
|
1 2 3 4 5 6 7 8 9 10 11
| HashMap<String, Integer> countMap = new HashMap<String, Integer>(); 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上被评为最好的方式。
参考文档