@Test publicvoidtestJDK_WordCount(){ String string = "I have a dream ! I dream one day I can go everywhere I wish !"; String[] words = string.split(" "); Map<String, Integer> countMap = new HashMap<>(); for (String word : words) { Integer count = countMap.get(word); if (count == null) { countMap.put(word, 1); } else { countMap.put(word, count + 1); } } Set<Map.Entry<String, Integer>> entrySet = countMap.entrySet(); for (Map.Entry<String, Integer> entry : entrySet) { System.out.println(entry.getKey() + ":" + entry.getValue()); } }
Guava实现
1 2 3 4 5 6 7 8 9 10 11
@Test publicvoidtestGuava_WordCount(){ String string = "I have a dream ! I dream one day I can go everywhere I wish !"; String[] words = string.split(" "); List<String> wordList = Arrays.asList(words); Multiset<String> multiset = HashMultiset.create(); multiset.addAll(wordList); for (String word : multiset.elementSet()) { // 返回不重复元素集合 System.out.println(word + ":" + multiset.count(word)); } }