我已经提供了一个应用程序,当给出关键字时,例如打印500条最新鸣叫。 “猫”。Java - 鸣叫计数器
我想用一个String.split()
用正则表达式分割的鸣叫的所有单词,然后使用HashMap
存储每个字,并使用循环递增每个字的整数值,每次它在微博中提到。
我已经提供了一个应用程序,当给出关键字时,例如打印500条最新鸣叫。 “猫”。Java - 鸣叫计数器
我想用一个String.split()
用正则表达式分割的鸣叫的所有单词,然后使用HashMap
存储每个字,并使用循环递增每个字的整数值,每次它在微博中提到。
应该是这样的:
for (String word : tweetText.split("\\s+")) {
wordMap.put(word, wordMap.getOrDefault(word, 0) + 1);
}
wordMap.getOrDefault(word, 0)
可能仅利用Java 8中的代码将您的鸣叫分成单独的单词和计算每个鸣叫感谢您的地图的话。
您可以使用Java 8流:
String[] words = tweetText.split(" ");
Map<String, Integer> wordCount = Arrays.stream(words)
.collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));
如果你想这样做的情况下在敏感:
Map<String, Integer> wordCount = Arrays.stream(words)
.map(String::toLowerCase)
.collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));
只查找特定的词:
Map<String, Integer> wordCount = Arrays.stream(words)
.map(String::toLowerCase)
.filter(word -> wordsToMatch.contains(word))
.collect(Collectors.toMap(word -> word, word -> 1, Integer::sum));
在哪里wordsToMatch可以是您正在查找的单词集或单词列表。
我将延伸HashMap<String, Integer>
是提供一种使用该值作为计数器的put(key)
:
class WordCounter extends HashMap<String, Integer> {
public void put(String key) {
Integer number = this.get(key);
this.put(key, number == null ? 1 : number + 1);
}
public static void main (String[] args) throws java.lang.Exception
{
WordCounter wc = new WordCounter();
for(String word : "this is a test and this is too".split(" ")) {
wc.put(word);
}
System.out.println(wc);
}
}
输出:
{a=1, test=1, too=1, and=1, this=2, is=2}