始める無料で始める

テキスト分析アプリケーションの実装

ドキュメント内の単語の出現頻度を数えるテキスト分析アプリケーションを開発しています。単語の検索に対して最適な時間計算量となる実装が必要です。

この演習はコースの一部です

Javaコード最適化

コースを見る

演習の手順

  • その単語が頻度マップにすでにある場合は、currentCount を取得します。
  • それをインクリメントし、更新後の値で頻度マップを更新します。
  • これまで頻度マップに単語がなかった場合は、追加します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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 = ____.get(____);
                // Increment the frequency of the word
                frequencyMap.put(____, currentCount + 1);
            } else {
                // If the frequency map does not have the word, add it.
                ____.____(word, 1);
            }
        }
        
        return frequencyMap;
    }
}
コードを編集して実行