"分拣" 思路 统计每个单词出现的次数
package collection.map; public class Letter { public String name; public int count; }
package collection.map; /* * 统计每个单词出现的次数 * "分拣" 思路 * 1、为所有key创建容器 * 之后容器中存放对应value * 2、第一次创建容器,并存放值value * 第二次之后,直接使用容器存放值 */ import java.util.HashMap; import java.util.Map; import java.util.Set; public class MapDemo01 { private static void test1(String str) { String[] strArr = str.split(" "); //分割字符串 Map<String,Letter> letterMap = new HashMap<String, Letter>(); for(String key : strArr) { Letter col = null; if(null == (col = letterMap.get(key))) { col = new Letter(); col.count = 1; letterMap.put(key, col); } else { col.count++; } } Set<String> keys = letterMap.keySet(); for(String key:keys) { Letter col = letterMap.get(key); System.out.println("单词:"+key+", 次数: "+col.count); } } private static void test2(String str) { String[] strArr = str.split(" "); Map<String,Integer> letterMap = new HashMap<String,Integer>(); for(String temp : strArr) { int count = 0; if(letterMap.containsKey(temp)) { count = letterMap.get(temp); } letterMap.put(temp, ++count); } //输出Map的值 Set<String> keys = letterMap.keySet(); for(String key:keys) { System.out.println("单词:"+key+",次数:"+letterMap.get(key)); } } public static void main(String[] args) { String str = "you know new york , you need new york . you know you need unique new york ."; test1(str); System.out.println("-----------"); test2(str); } }
I don't extravagant hope to change the world, only hope this world will not change me.