- Java 컬렉션 프레임워크는 데이터를 효율적으로 저장하고 조작할 수 있는 다양한 클래스와 인터페이스를 제공한다.
- 그 중 Map 인터페이스는 키(key)와 값(value)의 쌍으로 데이터를 저장하는 데 사용된다.
# Map 인터페이스
- 키와 값의 쌍을 저장하는 구조를 제공한다.
- 키는 고유해야 하며, 각 키는 하나의 값과 연결된다.
- 주소 메서드
put(K key, V value): 키와 값을 추가한다.
get(Object key): 키에 해당하는 값을 반환한다.
remove(Object key): 키에 해당하는 값을 제거한다.
containsKey(Object key): 키가 존재하는지 확인한다.
containsValue(Object value): 값이 존재하는지 확인한다.
size(): 맵의 크기를 반환한다.
isEmpty(): 맵이 비어 있는지 확인한다.
# HashMap
- 가장 많이 사용되는 Map 구현 클래스 중 하나이다.
- 해싱을 사용하여 데이터를 저장하며, 키와 값의 쌍이 해시 테이블에 저장된다.
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
System.out.println("apple: " + map.get("apple"));
System.out.println("banana: " + map.get("banana"));
map.remove("banana");
System.out.println("banana (after removal): " + map.get("banana"));
if (map.containsKey("orange")) {
System.out.println("orange is in the map");
}
if (map.containsValue(10)) {
System.out.println("A value 10 is in the map");
}
System.out.println("Size of the map: " + map.size());
System.out.println("Is map empty? " + map.isEmpty());
}
}
# LinkedHashMap
HashMap과 유사하지만, 삽입 순서를 유지한다.
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
}
}
# TreeMap
import java.util.Map;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
Map<String, Integer> map = new TreeMap<>();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
for (String key : map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
}
}