- 키(Key)와 값(Value)을 쌍으로 저장하고, 키를 이용해 빠르게 검색, 삽입, 삭제가 가능한 자료구조
- 키를 해시 함수(Hash Function)로 변환 → 배열(버킷) 인덱스로 사용
- 충돌(Collision)이 발생하면 별도의 처리 필요
- 복잡도
- 평균: O(1) (검색, 삽입, 삭제)
- 최악: O(n) (충돌이 많거나 해시 함수 품질 낮음)
문제 유형
- 데이터베이스 인덱스
- 캐시 구현 (LRU 캐시 등)
- 중복 제거 / 카운팅
- 연결된 데이터 조회 (키로 빠르게 접근)
코드 예시
import java.util.HashMap;
public class HashTableExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 2);
map.put("orange", 5);
System.out.println("apple의 값: " + map.get("apple"));
System.out.println("banana 존재? " + map.containsKey("banana"));
map.remove("banana");
System.out.println("banana 존재? " + map.containsKey("banana"));
for (String key : map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
}
}
import java.util.HashMap;
public class WordCountExample {
public static void main(String[] args) {
String[] words = {"apple", "banana", "apple", "orange", "banana", "apple"};
HashMap<String, Integer> countMap = new HashMap<>();
for (String word : words) {
countMap.put(word, countMap.getOrDefault(word, 0) + 1);
}
System.out.println(countMap);
}
}