本文共 3228 字,大约阅读时间需要 10 分钟。
当需要对元素进行计数时,HashMap非常有用,如下例子,统计一个字符串中每个字符出现的次数:
package simplejava;import java.util.HashMap;import java.util.Map.Entry;public class Q12 { public static void main(String[] args) { HashMapcountMap = new HashMap (); // .... 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 e : countMap.entrySet()){ System.out.println((char)(int)e.getKey() + " " + e.getValue()); } }}
输出结果:
Mapmp = new 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()); }
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{ 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 }}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 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); }}
虽然有很多种方法来对HashMap进行排序,但以上这种方法在stackoverflow中是最被推崇的;
注:使用了一个比较器Comparator对TreeMap排序,该比较器比较key的方式是取出key对应的value进行大小比较;
本文转自风一样的码农博客园博客,原文链接:http://www.cnblogs.com/chenpi/p/5493678.html,如需转载请自行联系原作者