[分拣思想]——对象计数

分拣思想

    现在我们想记录这句话里单词出现的次数,"this is a cat and that is a mice and where is the food"。有两种思路:
    一:先遍历单词一遍,在遍历的过程中,逐个为单词创建容器,并计数。
public class Letter {
	private String name;
	private int count;
	public Letter(){
	}
	public Letter(String name, int count) {
		super();
		this.name = name;
		this.count = count;
	}
	//创建了name和count的set与get方法
}
   Letter类包含了单词名称和自身数量的属性。
public static void main(String[] args) {
	String str="this is a cat and that is a mice and where is the food";
	String[] strArray=str.split(" ");//分割字符串
	Map<String, Letter> letters=new HashMap<String,Letter>();
	for(String temp:strArray){
		if (!letters.containsKey(temp)) {
			letters.put(temp, new Letter());
		}
		Letter col=letters.get(temp);//那对象并计数
		col.setCount(col.getCount()+1);
	}
	//输出map
	Set<String> keys=letters.keySet();
	for(String key:keys){
		Letter col=letters.get(key);
		System.out.println("字母: "+key+"次数"+col.getCount());
	}
}
    二:先遍历单词一遍,为所有的单词创建容器,然后来计数。
public static void main(String[] args) {
	String str="this is a cat and that is a mice and where is the food";
	String[] strArray=str.split(" ");//分割字符串
	Map<String, Letter> letters=new HashMap<String,Letter>();
	for(String temp:strArray){
		if (!letters.containsKey(temp)) {
		<span style="white-space:pre">	</span>letters.put(temp, new Letter());
		}//所有的key都有容器了
	}
	for(String temp:strArray){
		Letter col=letters.get(temp);//直接使用容器
		col.setCount(col.getCount()+1);
	}
	//输出map
	Set<String> keys=letters.keySet();
	for(String key:keys){
		Letter col=letters.get(key);
		System.out.println("字母: "+key+"次数"+col.getCount());
	}
}
          Key就是单词的名称,Value就是对应的Letter对象,里面包含了单词的名称和其数量。

           


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值