基于Map实现的频率统计代码

四月 2, 2008 | 标签 java  map   | 浏览
评论 0
使用泛型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<T> {
    private Map<T, Integer> m = new HashMap<T, Integer>();
 
    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<Integer> s = new Statistics<Integer>();
       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));
    }
}

结果:




发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。