分拣存储:
统计 各个单词 出现的次数
this is a cat and that is a mice and where is the food ?
- 直接分拣-HashMapDemo
package hashmap.sortout.worldcount;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapDemo {
/**
* 分拣存储:
* 统计 单词 出现的次数
* this is a cat and that is a mice and where is the food ?
*
* 思路
* 1、分割字符串
* 2、分拣存储
* 3、按要求查看 单词出现的次数
*/
public static void main(String[] args) {
// 1、分割字符串
String[] arr ="this is a cat and that is a mice and where is the food ?".split(" ");
// 2、分拣存储
Map<String,Integer> map =new HashMap<String,Integer>();
for(String key:arr){
System.out.println(key );//每个单词
if(!map.containsKey(key)){ //查看是否存在该单词,不存在
map.put(key, 1);
}else{ //存在
map.put(key, map.get(key)+1);
}
}
//3、查看每个单词出现的次数
Set<String> keySet =map.keySet();
//获取对象
Iterator<String> it =keySet.iterator();
while(it.hasNext()){//判断
String key =it.next();
Integer value =map.get(key);
System.out.println(key+"-->"+value);
}
}
}
- 加入面向对象
1.创建一个Letter类来存储分拣结果-Letter
package hashmap.sortout.worldcount;
public class Letter {
private String world; //单词
private int count; //次数
public Letter() {
}
public Letter(String world) {
super();
this.world = world;
}
public String getWorld() {
return world;
}
public void setWorld(String world) {
this.world = world;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
2.实现分拣功能并把分拣结果装到Letter中-HashMapLetterImpl
package hashmap.sortout.worldcount;
import java.util.HashMap;
import java.util.Map;
public class HashMapLetterImpl {
/**
* 分拣存储: 1:N
* 统计 单词 出现的次数
* this is a cat and that is a mice and where is the food ?
*
* 思路
* 1、分割字符串
* 2、分拣存储
* 3、按要求查看 单词出现的次数
* 4、加入面向对象
*/
public static void main(String[] args) {
// 1、分割字符串
String[] arr ="this is a cat and that is a mice and where is the food ?".split(" ");
// 2、分拣存储
Map<String,Letter> map =new HashMap<String,Letter>();
for(String key:arr){
//第一次查看是否 存在 袋子
if(!map.containsKey(key)){ //不存在
map.put(key, new Letter(key));//准备好袋子
}
//获取袋子
Letter value =map.get(key);
value.setCount(value.getCount()+1);//装东西
/**
Letter value =map.get(key);
if(null==value){
value =new Letter();
map.put(key, value);
}
value.setCount(value.getCount()+1);//装东西
*/
}
//3、查看每个单词出现的次数
for(String key:map.keySet()){
Letter value =map.get(key);
System.out.println(key+"-->"+value.getCount());
}
}
}