java统计字数_Java 8的字数统计

我正在尝试在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。我该如何纠正?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值