Java – word counting using streams

I try to use streams in Java to calculate words This is what I tried:

public static int countWords(String s) {
    return s.chars().reduce((x,y) -> {
        if((char)y == ' ')
            ++x;
        return x;
    }).orElse(0);
}

But countwords ("ASD") returns 97 Why? I think the intstream returned by chars is actually composed of chars So, I just convert it to char What's up?

Solution

Although your problem refers to calculating words, your code seems to be designed to calculate spaces If this is your intention, I would suggest:

input.chars().filter(Character::isSpaceChar).count();

This can avoid many conversion complications in the code, and if it makes more sense for your domain, you can change it to iswhitespace

However, if you want to calculate words, the simplest solution is to split on white space and then calculate non empty words:

Pattern.compile("\\s+").splitAsStream(input).filter(word -> !word.isEmpty()).count();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>