Eine Textanalyse-Anwendung implementieren
Du entwickelst eine Textanalyse-Anwendung, die die Häufigkeit von Wörtern in einem Dokument zählen muss. Du sollst eine Lösung mit optimaler Zeitkomplexität für Wortnachschläge implementieren.
Diese Übung ist Teil des Kurses
Codeoptimierung in Java
Anleitung zur Übung
- Rufe den
currentCountfür das Wort ab, wenn es bereits in der Frequency-Map enthalten ist. - Erhöhe ihn und aktualisiere die Frequency-Map mit dem neuen Wert.
- Wenn das Wort bisher nicht in der Frequency-Map war, füge es hinzu.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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;
}
}