普通方法
package collection03;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/***
* 分拣存储 1:N
* 统计单词出现的次数
* @author zw
*
*/
public class MapDemo02 {
public static void main(String[] args){
String[] arr ="I love you not for who you are, but for who I am before you".split(" ");
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); }
}
Set<String> keySet = map.keySet();//获取对象
Iterator<String> ter =keySet.iterator();
while(ter.hasNext()){
String key = ter.next();
Integer value = map.get(key);
System.out.println(key+"出现了"+value+"次");
}
}
}
利用JavaBean做
package collection03;
public class Words {
private String word;
private int counts;
public Words(String word) {
super();
this.word =word;
}
public Words(){
}
public Words(String word, int counts) {
super();
this.word = word;
this.counts = counts;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getCounts() {
return counts;
}
public void setCounts(int counts) {
this.counts = counts;
}
}
package collection03;
import java.util.HashMap;
import java.util.Map;
/***
* 分拣存储 1:N
* 统计单词出现的次数
* @author zw
*
*/
public class MapDemo01 {
public static void main(String[] args){
String[] arr ="I love you not for who you are, but for who I am before you".split(" ");
Map<String,Words> map = new HashMap<String,Words>();
for(String key:arr){
if(!map.containsKey(key)){
map.put(key, new Words(key));
}
Words value = map.get(key);
value.setCounts(value.getCounts()+1);
}
for(String key:map.keySet()){
Words value = map.get(key);
System.out.println(key+"出现了"+value.getCounts()+"次");
}
}
}