자바의 Map
자료구조는 키-값 쌍(Key-Value Pair)을 저장하는 컬렉션입니다. 각 키는 고유하며, 하나의 키는 하나의 값과 매핑됩니다. Map
인터페이스는 자바에서 가장 많이 사용되는 자료구조 중 하나입니다.
Map
구현 클래스입니다. 해싱을 사용하여 키-값 쌍을 저장하며, 평균적으로 O(1)의 시간 복잡도를 가집니다.HashMap
과 유사하지만, 삽입 순서를 유지합니다.HashMap
과 유사하지만, 동기화되어 있어 스레드 안전합니다.Map
인터페이스의 주요 메서드put(K key, V value)
:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
get(Object key)
:
null
을 반환합니다.Integer value = map.get("apple"); // 1
remove(Object key)
:
map.remove("banana");
containsKey(Object key)
:
boolean hasApple = map.containsKey("apple"); // true
containsValue(Object value)
:
boolean hasValue1 = map.containsValue(1); // true
keySet()
:
Set
을 반환합니다.Set<String> keys = map.keySet();
values()
:
Collection
을 반환합니다.Collection<Integer> values = map.values();
entrySet()
:
Set<Map.Entry<K, V>>
를 반환합니다.Set<Map.Entry<String, Integer>> entries = map.entrySet();
Map
사용 예시import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// HashMap 생성
Map<String, Integer> map = new HashMap<>();
// 요소 추가
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
// 요소 접근
Integer appleValue = map.get("apple");
System.out.println("apple: " + appleValue); // apple: 1
// 요소 제거
map.remove("banana");
// 키 존재 여부 확인
boolean hasCherry = map.containsKey("cherry");
System.out.println("Has cherry: " + hasCherry); // Has cherry: true
// 값 존재 여부 확인
boolean hasValue2 = map.containsValue(2);
System.out.println("Has value 2: " + hasValue2); // Has value 2: false
// 모든 키 출력
for (String key : map.keySet()) {
System.out.println("Key: " + key);
}
// 모든 값 출력
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
// 모든 키-값 쌍 출력
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
Map
은 키와 값을 쌍으로 저장합니다.HashMap
과 LinkedHashMap
은 null
키와 값을 허용하지만, Hashtable
은 허용하지 않습니다.HashMap
은 순서를 보장하지 않지만, LinkedHashMap
은 삽입 순서를, TreeMap
은 키의 정렬 순서를 보장합니다.이러한 특징과 메서드를 통해 Map
은 다양한 상황에서 효율적으로 데이터를 저장하고 조회할 수 있는 자료구조입니다.