#86 Counting Word Occurrences in a List of Strings

Companies:
OTR
Themes:
JavaStreams & LambdasPractice

Write a method that accepts a list of strings and counts how many times each word or phrase occurs in the list. Ignore spaces and letter case.

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class WordCounter {

    public static void main(String[] args) {
        // Create a list of strings
        List<String> list = Arrays.asList(
            "Hello world",
            "hello   World",
            "HELLO WORLD!",
            "    Java is the best language",
            "Java is the best   language"
        );

        Map<String, Long> wordCountMap = countWordOccurrences(list);

        wordCountMap.forEach((word, count) -> System.out.println(word + " " + count));
}

    public static Map<String, Long> countWordOccurrences(List<String> list) {
        return list.stream()
        //your code
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in