Get startedGet started for free

Implementing a text analysis application

You're developing a text analysis application that needs to count the frequency of words in a document. You need to implement a solution with optimal time complexity for word lookups.

This exercise is part of the course

Optimizing Code in Java

View Course

Exercise instructions

  • Retrieve the frequency of the word when it is already in the frequency map.
  • Increment it and update the frequency map the updated value.
  • If the word was not in the frequency map until now, add it.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        TextAnalyzer analyzer = new TextAnalyzer();
        
        List words = Arrays.asList(
            "Java", "is", "a", "programming", "language", 
            "Java", "is", "widely", "used", "for", "building", "applications",
            "Many", "programmers", "use", "Java", "for", "web", "development", "and", "Android", "apps"
        );
        
        Map wordFrequency = analyzer.buildWordFrequencyMap(words);
        
        System.out.println("Word frequency analysis:");
        for (Map.Entry entry : wordFrequency.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue() + " occurrences");
        }
    }
}

class TextAnalyzer {
    public Map buildWordFrequencyMap(List words) {
        Map frequencyMap = new HashMap();
        
        for (String word : words) {
            if (word.isEmpty()) {
                continue;
            }
            
            word = word.toLowerCase();
            
            if (frequencyMap.containsKey(word)) {
                // Retrieve the frequency of the word
                int currentCount = ____;
                // Increment the frequency of the word
                frequencyMap.put(____, currentCount + 1);
            } else {
                // If the frequency map does not have the word, add it.
                ____
            }
        }
        
        return frequencyMap;
    }
}
Edit and Run Code