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

使用泛型 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));

    }

}
结果:
{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,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值