public interface Map<K,V> {
interface Entry<K,V> {
K getKey();
V getValue();
V setValue(V value);
boolean equals(Object o);
int hashCode();
// ...
}
}
- Map.Entry는 Map 내부에서 key-value 쌍을 나타내는 인터페이스
- Map은 단순히 key와 value의 매핑 구조이므로 하나의 단위로 다루기 위한 구조체가 Entry
- 정렬된 Map (TreeMap), 변경 가능한 Map 탐색에서 자주 사용됨
주요 메서드
K getKey()
- key 반환
V getValue()
- value 반환
V setValue(V value)
- value 변경
boolean equals(Object o)
int hashCode()
- Entry 간 비교를 위해 오버라이딩 가능
static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey()
static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue()
- `comparingByKey()` : key 기준으로 정렬
- `comparingByValue()` : value 기준으로 정렬
public interface Map<K,V> {
Set<Map.Entry<K,V>> entrySet();
}
- Map에서 Map.Entry를 사용하기 위해 이용하는 함수
- `entrySet()`을 사용한 반복은 `keySet()` 보다 빠름
사용 예시 1️⃣
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
// Entry를 사용한 반복
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
사용 예시 2️⃣
Map<String, Integer> map = new HashMap<>();
map.put("banana", 2);
map.put("apple", 5);
map.put("cherry", 1);
// key 기준 정렬
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
//.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 역순 정렬
.forEach(entry -> System.out.println(entry.getKey() + " = " + entry.getValue()));
// value 기준 정렬
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
//.sorted(Map.Entry.comparingByValue((v1, v2) -> Integer.compare(v2, v1))) // value 내림차순
.forEach(entry -> System.out.println(entry.getKey() + " = " + entry.getValue()));
'Java' 카테고리의 다른 글
상속(inheritance) - JAVA (0) | 2025.05.01 |
---|---|
자바의 다형성(polymorphism) (0) | 2025.05.01 |
Comparable (java.lang), Comparator (java.util) (1) | 2025.04.30 |
Collection 프레임워크 (0) | 2025.04.29 |
JDK, JRE, JVM (1) | 2025.04.22 |