# 맵(Map)
# 맵이란?
Key와 Value 쌍으로 이루어져, 키값을 통해 값에 접근을 할 수 있도록 만들어진 자료구조입니다.
주의점!
- Key의 중복을 허용하지 않습니다.
- Value는 중복 값을 허용합니다.
# 맵의 종류와 특징
- HashMap
- Key에 대한 중복이 없으며 순서를 보장하지 않습니다.
- Key와 Value 값으로 null을 허용합니다.
- 동기화가 보장되지 않습니다.
- 검색에 가장 뛰어난 성능을 가집니다.
- TreeMap
- 레드블랙 트리를 기반으로 키와 값을 저장합니다.
- key값을 기준으로 오름차순 정렬되고 빠른 검색이 가능합니다.
- 정렬 기준은 '숫자>알파벳 대문자>알파벳 소문자>한글' 입니다.
- 저장 시 정렬을 하기 때문에 시간이 다소 오래 걸립니다.
- LinkedHashMap
- 입력된 순서를 보장합니다.
# 맵의 사용법
자바의 map은 인터페이스이기 때문에, map을 구체화한 클래스 중 HashMap을 사용해보겠습니다.
public class MapTest {
public void maptest() {
//맵 생성 : <Key, Value> 순으로 원하는 타입을 지정합니다.
HashMap<Integer, String> hMap = new HashMap<Integer, String>();
//put : (Key, Value)순으로 원하는 값을 넣어줍니다.
hMap.put(1, "hello");
hMap.put(2, "world");
hMap.put(3, "HashMap");
hMap.put(4, "TreeMap");
//get : Key값을 통해 원하는 value값을 return 받습니다. (map에 해당 key-value가 그대로 남아있음)
System.out.println(hMap.get(1));
//containsKey : map에 해당하는 key값이 있는 지 없는 지 반환해줍니다.
System.out.println(hMap.containsKey(3));
//containsValue : map에 해당하는 value값이 존재하는지 반환해줍니다.
System.out.println(hMap.containsValue("HashMap"));
//size : map의 사이즈를 반환해줍니다.
System.out.println(hMap.size());
//remove : map에서 입력한 key값에 해당하는 value를 꺼내줍니다. (map에 해당 key-value가 사라짐)
System.out.println(hMap.remove(2));
//출력방법 1: EntrySet
for(Map.Entry<Integer,String> mEntry : hMap.entrySet()) {
System.out.println("EntrySet : " + mEntry.getKey() + ", " + mEntry.getValue());
}
//출력방법 2 : KeySet
for(int key : hMap.keySet()) {
System.out.println("KeySet : " + key + ", " + hMap.get(key));
}
//출력방법 3 : EntrySet Iterator
Iterator<Map.Entry<Integer, String>> entryIter = hMap.entrySet().iterator();
while(entryIter.hasNext()) {
Map.Entry<Integer, String> entry = entryIter.next();
System.out.println("EntrySet Iterator : " + entry.getKey() + ", " + entry.getValue());
}
//출력 방법 4 : KeySet Iterator
Iterator<Integer> keyIter = hMap.keySet().iterator();
while(keyIter.hasNext()) {
int key = keyIter.next();
System.out.println("KeySet Iterator : " + key + ", " + hMap.get(key));
}
}
}
TreeMap은 순서가 존재하기 때문에, firstKey(), firstEntry(), lastKey(), higherKey(), lowerKey() 등을 사용할 수 있습니다.
# HashTable이란?
HashTable은 Thread safe하지 않은 HashMap과 달리, 동기화가 보장되어 병렬 프로그래밍이 가능합니다.
- HashMap 보다 처리속도가 느립니다.
- Key와 Value값으로 null을 허용하지 않습니다.
- 정렬을 보장하지 않는 unordered_map으로 구현합니다.
- 삽입, 삭제, 탐색 시 평균적으로 O(1)의 시간복잡도를 가집니다.
# 참고자료
출처: https://cocoon1787.tistory.com/527
출처: https://readerr.tistory.com/37