package map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* this is a cat and that is mice and where is the food?
* 统计每个单词出现的次数
*
* 存储到map中
* key:string
* value:自定义类型
*
* 分拣 思路
* 1、为所有key创建容器
* 之后容器中存放对应value
* 2、第一次创建容器,并存放值value
* 第二次之后,直接使用容器存放值
*
* @author zmx
*
*/
public class Demo01 {
/**
*
*/
public static void main(String[] args) {
String str="this is a cat and that is mice and where is the food?";
//分割字符串
String[] strArray=str.split(" ");
//存储到map中
Map<String, Letter> letters =new HashMap<String,Letter>();
for(String temp:strArray){
if(!letters.containsKey(temp)){//这里判断要letter容器中没有这个键才添加的。
letters.put(temp,new Letter());
}
// Letter col=letters.get(temp);//取出temp键对应的值
// col.setCount(col.getCount()+1);
Letter coLetter=letters.get(temp);
coLetter.setCount(coLetter.getCount()+1);
}
//输出
Set<String> keys=letters.keySet();//keySet()得到键的
for(String key:keys){
Letter col=letters.get(key);
System.out.println("字母:"+key+",次数"+col.getCount());
}
}
}
map的分拣思想
最新推荐文章于 2024-03-06 00:30:00 发布