IniziaInizia gratis

Implementare un'applicazione di analisi del testo

Stai sviluppando un'applicazione di analisi del testo che deve contare la frequenza delle parole in un documento. Devi implementare una soluzione con complessità temporale ottimale per le ricerche delle parole.

Questo esercizio fa parte del corso

Ottimizzazione del codice in Java

Visualizza il corso

Istruzioni dell'esercizio

  • Recupera currentCount per la parola quando è già presente nella mappa delle frequenze.
  • Incrementalo e aggiorna la mappa delle frequenze con il valore aggiornato.
  • Se la parola non era ancora nella mappa delle frequenze, aggiungila.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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;
    }
}
Modifica ed esegui il codice