使用泛型T代表所要統計資訊的類,應該有效的定義該類的equals()和hasCode()。
statistics()方法進行關鍵字統計。
getAllKeysStatistics()方法傳回底層的Map,即所有的鍵-值對。
getAllKeys()方法傳回所有key組成的Set。
getKeyStatistics()方法傳回單個确定Key的統計資訊。
測試例使用10000個随機整型數(0~9)來統計它們的産生頻率。
<b>package</b> com.zj.col;
<b>import</b> java.util.HashMap;
<b>import</b> java.util.Map;
<b>import</b> java.util.Random;
<b>public</b> <b>class</b> Statistics<T> {
<b>private</b> Map<T, Integer> m = <b>new</b> HashMap<T, Integer>();
<b>public</b> <b>void</b> statistics(T t) {
Integer freq = m.get(t);
m.put(t, freq == <b>null</b> ? 1 : freq + 1);
}
<b>public</b> <b>void</b> getAllKeysStatistics() {
System.out.println(m);
<b>public</b> <b>void</b> getAllKeys() {
System.out.println(m.keySet());
<b>public</b> <b>int</b> getKeyStatistics(T t) {
<b>return</b> m.get(t) == <b>null</b> ? 0 : m.get(t);
<b>public</b> <b>static</b> <b>void</b> main(String[] args) {
Random rand = <b>new</b> Random();
Statistics<Integer> s = <b>new</b> Statistics<Integer>();
<b>for</b> (<b>int</b> i = 0; i < 10000; i++) {
// Produce a number between 0 and 9:
<b>int</b> 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:0
Key 0:1038
本文轉自zhangjunhd51CTO部落格,原文連結:http://blog.51cto.com/zhangjunhd/69949,如需轉載請自行聯系原作者