Map은 리스트나 배열처럼 순차적으로 해당 요소 값을 구하지 않고 key
를 통해 value
를 얻는다.
Map의 특징
{이름:홍길동}
, {고양이:cat}
과 같이 대응 관계를 쉽게 표현할 수 있는 자료형put
메소드를 이용하여 맵에 원하는 값을 매칭시켜서 추가할 수 있다.
HashMap
HashMap은 자바에서 제공하는 맵(Map) 인터페이스를 구현한 클래스 중 하나로 해시 테이블(hash table)을 기반으로한 맵이다.
키(key)와 값(value)의 쌍을 저장하고 검색하는 데 사용된다.
import java.util.HashMap;
public class MapExample {
public static void main(String[] args) {
Map<String, String> dictionary = new HashMap<>();
dictionary.put("chicken", "닭");
dictionary.put("hippo", "하마");
}
}
chicken:닭
, hippo:하마
값을 dictionary에 넣어주었다.
get
: key에 해당하는 value값을 얻기 위해서 사용하는 메소드
System.out.println(dictionary.get("chicken"));
해석 : dictionary에서 chicken에 해당하는 value 가져오렴
닭
데이터를 제거할 때도 put
메소드를 사용할 수 있다.
dictionary.put("chicken", null);
해석 : dictionary에 있는 chicken 키에 해당하는 값 null로 매칭하렴
이렇게 하면 chicken에 해당하는 값이 null값으로 변경되지만 데이터는 아직 남아있는 상태라서 size 명령어로 사이즈 크기를 확인하면 데이터가 그대로 남아있는 것으로 인식된다.
그래서 깔끔하게 지워버릴 때는 remove
를 사용하면 된다.
dictionary.remove("chicken");
dictionary.remove("hippo");
키값에 해당되는 데이터(key, value)를 삭제 후 그 value값을 리턴하는 명령어
System.out.println(dictionary.remove("chicken")); //"닭" 출력
size
: Map의 개수를 리턴하는 메소드
if (dictionary.isEmpty()) {
System.out.println("단어가 하나도 없습니다.");
System.exit(0);
} else {
System.out.println(dictionary.size() + " 개의 단어가 있습니다.");
}
System.out.println(dictionary.size() + "개의 단어가 있습니다.");
dictionary가 비어 있는 상태인지 isEmpty()
로 확인하고 맞다면 "단어가 하나도 없습니다."
를 출력한다.
아니라면 size
로 dictionary의 개수를 확인해서 출력한다.
keySet()
메서드는 맵의 모든 키를 모아서 Set 자료형으로 리턴한다.
import java.util.HashMap;
public class Practice {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("people", "사람");
map.put("soccer", "축구");
System.out.println(map.keySet()); // [people, soccer] 출력
}
}
반복문으로 표현하기(for)
public class Practice {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("people", "사람");
map.put("soccer", "축구");
Collection<String> keys = map.keySet();
for (String abc : keys) {
System.out.println(abc);// [people, soccer] 출력
}
}
}
키랑 값을 동시에 보려면 어떻게 해야할까?
entryset
: 맵에 저장된 키-값 데이터를 표현하는 entry 객체의 집합(Set)을 반환한다.
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Practice {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("people", "사람");
map.put("soccer", "축구");
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
String abc = entry.getKey();
String korean = entry.getValue();
System.out.println(abc + ": " + korean);
}
}
}
출력 결과
soccer: 축구
people: 사람
entrySet()
메소드를 사용하여 Map.Entry
객체들의 Set을 얻은 후 반복문을 통해 각 Map.Entry
객체에서 키와 값을 추출하여 출력한다.
2023.06.03 작성