Collection类的应用--统计出现最多的字符

一个字符串中可能包含 a z 中的多个字符,如有重复,求出现次数最多的那个字母及次数,如有多个重复则都求出来。                                                                                   
  1. import java.util.*;
  2. import java.util.Collections;
  3. public class  LetterCount
  4. {
  5.     public void getLetterCount(String str)
  6.     {
  7.         ArrayList<String> lists = new ArrayList<String>();
  8.         HashSet<String> hset = new HashSet<String>();
  9.         char[] ss = str.toCharArray();
  10.         for(int i=0; i<ss.length; i++)
  11.         {
  12.             lists.add(String.valueOf(ss[i]));
  13.             hset.add(String.valueOf(ss[i]));
  14.         }
  15.         System.out.println("共有字母"+hset.size()+"个!");
  16.         Collections.sort(lists);
  17.         Iterator it = hset.iterator();  
  18.         while(it.hasNext())
  19.         {
  20.             String os = (String)it.next();
  21.             int begin = lists.indexOf(os);
  22.             int last = lists.lastIndexOf(os);
  23.             int count = last-begin+1;
  24.             System.out.println("字母"+os+": 共"+count+"个");
  25.         }
  26.     }
  27.             
  28.     public static void main(String[] args) 
  29.     {
  30.         LetterCount lc = new LetterCount();
  31.         lc.getLetterCount(args[0]);
  32.     }
  33. }

我的运行结果:
D:/backup/myclass>java LetterCount yekmaakkccekymbvb
共有字母8个!
字母k: 共4个
字母m: 共2个
字母a: 共2个
字母c: 共2个
字母y: 共2个
字母b: 共2个
字母v: 共1个
字母e: 共2个

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值