Java word count program

后端 未结 22 1453
北荒
北荒 2020-12-09 06:48

I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string

22条回答
  •  爱一瞬间的悲伤
    2020-12-09 07:01

    My implementation, not using StringTokenizer:

    Map getWordCounts(List sentences, int maxLength) {
        Map commonWordsInEventDescriptions = sentences
            .parallelStream()
            .map(sentence -> sentence.replace(".", ""))
            .map(string -> string.split(" "))
            .flatMap(Arrays::stream)
            .map(s -> s.toLowerCase())
            .filter(word -> word.length() >= 2 && word.length() <= maxLength)
            .collect(groupingBy(Function.identity(), counting()));
        }
    

    Then, you could call it like this, as an example:

    getWordCounts(list, 9).entrySet().stream()
                    .filter(pair -> pair.getValue() <= 3 && pair.getValue() >= 1)
                    .findFirst()
                    .orElseThrow(() -> 
        new RuntimeException("No matching word found.")).getKey();
    

    Perhaps flipping the method to return Map might be better.

提交回复
热议问题