使用泛型T代表所要统计信息的类,应该有效的定义该类的equals()和hasCode()。
statistics()方法进行关键字统计。
getAllKeysStatistics()方法返回底层的Map,即所有的键-值对。
getAllKeys()方法返回所有key组成的Set。
getKeyStatistics()方法返回单个确定Key的统计信息。
测试例使用10000个随机整型数(0~9)来统计它们的产生频率。
package com.zj.col;
import java.util.HashMap;import java.util.Map;import java.util.Random;public class Statistics { private Map m = new HashMap(); public void statistics(T t) { Integer freq = m.get(t); m.put(t, freq == null ? 1 : freq + 1); } public void getAllKeysStatistics() { System.out.println(m); } public void getAllKeys() { System.out.println(m.keySet()); } public int getKeyStatistics(T t) { return m.get(t) == null ? 0 : m.get(t); } public static void main(String[] args) { Random rand = new Random(); Statistics s = new Statistics(); for (int i = 0; i < 10000; i++) { // Produce a number between 0 and 9: int r = rand.nextInt(10); s.statistics(r); } s.getAllKeysStatistics(); s.getAllKeys(); System.out.println("Key -1:" + s.getKeyStatistics(-1)); System.out.println("Key 0:" + s.getKeyStatistics(0)); }}
结果:
{0=1038, 1=1014, 2=939, 3=987, 4=977, 5=974, 6=1036, 7=974, 8=1075, 9=986}[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]Key -1:0Key 0:1038
寂寞时,想想我的影子,我会在远方给你一个微笑;难过时,