Java
Map
Sun-Koo
2023. 3. 10. 16:21
Map 컬렉션은 key와 value의 쌍으로 값을 저장하는 컬렉션
Key 값은 중복 X (불가능)
Value 값은 중복 O (가능)
import java.util.*;
public class MapDemo {
public static void main(String[] args) {
HashMap<String, Integer> a = new HashMap<String, Integer>();
a.put("one", 1);
a.put("two", 2);
a.put("three", 3);
a.put("four", 4);
System.out.println(a.get("one"));
System.out.println(a.get("two"));
System.out.println(a.get("three"));
// MAP 반복 2가지 방법
iteratorUsingForEach(a);
iteratorUsingIterator(a);
}
static void iteratorUsingForEach(HashMap map){
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
System.out.println(entry.getKey() + " : " + entry.getValue());
// Map.Entry
// map.entrySet();에 담겨있는 메소드
// .getKety(), entry.getValue()
}
}
static void iteratorUsingIterator(HashMap map){
Set<Map.Entry<String, Integer>> entries = map.entrySet();
Iterator<Map.Entry<String, Integer>> i = entries.iterator();
while(i.hasNext()){
Map.Entry<String, Integer> entry = i.next();
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
}
Map에서 데이터를 추가할 때 사용하는 API는 put이다
put의 첫번째 인자는 값의 key이고, 두번째 인자는 key에대한 값(value)이다.
// 키값으로 가져오기
System.out.println(a.get("one"))
key를 이용해서 값을 가져올 수 있다.
Map에 저장된 데이터를 열거하는 방법
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
메소드 entrySet은 Map의 데이터를 담고 있는 Set을 반환한다.
반환한 Set의 값이 사용할 데이터 타입은 Map.Entry이다.
Map.Entry는 인터페이스인데 아래와 같은 API를 가지고 있다.
- getKey
- getValue
Map의 key, value를 조회할 수 있다.
데이터 타입의 교체
컬렉션을 사용할 때는 데이터 타입은 가급적 해당 컬렉션을 대표하는 인터페이스를 사용하는 것이 좋다
HashMap<String, Integer> a = new HashMap<String, Integer>();
HashMap은 Map 인터페이스를 구현하기 때문에 변수 a의 데이터 타입으로 Map을 사용할 수 있다.
Map<String, Integer> a = new HashMap<String, Integer>();