分拣思想
现在我们想记录这句话里单词出现的次数,"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对象,里面包含了单词的名称和其数量。