我正在尝试在Java 8中实现单词计数程序,但无法使其工作。该方法必须将字符串作为参数并返回Map。
当我以旧的Java方式进行操作时,一切正常。但是,当我尝试在Java 8中执行此操作时,它将返回一个映射,其中键为空且具有正确的出现次数。
这是我的Java 8风格的代码:
public Map countJava8(String input){
return Pattern.compile("(\\w+)").splitAsStream(input).collect(Collectors.groupingBy(e -> e.toLowerCase(), Collectors.reducing(0, e -> 1, Integer::sum)));
}
这是我在正常情况下会使用的代码:
public Map count(String input){
Map wordcount = new HashMap<>();
Pattern compile = Pattern.compile("(\\w+)");
Matcher matcher = compile.matcher(input);
while(matcher.find()){
String word = matcher.group().toLowerCase();
if(wordcount.containsKey(word)){
Integer count = wordcount.get(word);
wordcount.put(word, ++count);
} else {
wordcount.put(word.toLowerCase(), 1);
}
}
return wordcount;
}
主程序:
public static void main(String[] args) {
WordCount wordCount = new WordCount();
Map phrase = wordCount.countJava8("one fish two fish red fish blue fish");
Map count = wordCount.count("one fish two fish red fish blue fish");
System.out.println(phrase);
System.out.println();
System.out.println(count);
}
当我运行该程序时,输出如下:
{ =7, =1}
{red=1, blue=1, one=1, fish=4, two=1}
我认为该方法splitAsStream会将正则表达式中的匹配元素流式传输为Stream。我该如何纠正?