//Letter.java
package yzhou.map; /** * * @author 洋 * */ public class Letter { private String name; private int count; public Letter() { // TODO Auto-generated constructor stub } public Letter(String name) { super(); this.name = name; } public Letter(String name, int count) { super(); this.name = name; this.count = count; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
MapDemo02.java
package yzhou.map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * 分拣存储:1:N * 统计单词出现的次数 * this is a cat and that is a mice and where is the food? * @author 洋 * * *思路: *1.分割字符串 *2.分拣存储 *3.按要求查看单词出现的次数 * */ public class MapDemo02 { 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()); } } }