텍스트 분석 애플리케이션 구현하기
문서에서 단어의 출현 빈도를 세는 텍스트 분석 애플리케이션을 개발하고 있어요. 단어 조회의 시간 복잡도가 최적인 방식으로 해결해야 합니다.
이 연습은 강의의 일부입니다
Java 코드 최적화
연습 안내
- 빈도 맵에 단어가 이미 있을 때 해당 단어의
currentCount를 가져오세요. - 값을 1 증가시킨 뒤, 빈도 맵에 업데이트된 값으로 반영하세요.
- 지금까지 빈도 맵에 없던 단어라면 새로 추가하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
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;
}
}