分揀存儲:
統計 各個單詞 出現的次數
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());
}
}
}