프로그래밍 언어/Java

Java - Map과 HashMap

zerotoinfinite 2022. 11. 24. 20:35

Java - Map



목차

  1. Map의 사용 이유
  2. Map의 구현체
  3. HashMap의 생성자
  4. HashMap의 기능


1. Map의 사용 이유

  • Map은 <Key, Value> 형태로 데이터를 저장한다.
  • 연관 있는 데이터 끼리 묶어서 저장하고 싶다면, Map을 고려할 만 하다.
  • Key는 중복될 수 없지만 , Value는 중복될 수 있다.


2. Map의 구현체

  1. HashMap
  • 들어오는 데이터에 대한 hashCode를 기반으로 해시 값이 같은 값을 Entry 배열에 저장한다.
  • 데이터를 정렬하지 않는다.

  1. TreeMap
  • RedBlack Tree를 기반으로 데이터를 저장 및 관리한다.
  • Key 값을 기준으로 정렬한다.


3. HashMap의 생성자

  1. HashMap()
  • 새로운 빈 HashMap을 생성한다.
  • Capacity는 16, load factor는 0.75 이다.
Map<Integer> map = new HashMap<>();

  1. HashMap(Map<? extends K, ? extends V> m)
  • 인자로 받은 Map에 해당하는 새로운 hashMap을 생성한다.
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");
hashMap.put(2, "second");
hashMap.put(3, "third");

HashMap<Integer, String> newHashMap = new HashMap<>(hashMap);
// 1 : "first"
// 2 : "second"
// 3 : "third" 
// 순서 보장은 하지 않는다.

  1. HashMap(int initialCapacity)
  • capacity를 조정하여 HashMap을 생성할 수 있다. (Default capacity = 16)
HashMap<Integer, String> hashMap = new HashMap<>(32);
// capacity = 32인 hashMap 생성

  1. HashMap(int initialCapacity, float loadFactor)
  • capacity와 loadFactor를 조정하여 HashMap을 생성할 수 있다. (Default loadFactor = 0.75)
HashMap<Integer, String> hashMap = new HashMap<>(32, 0.9f);



4. HashMap의 기능

  1. put(K key, V value)
  • 데이터를 삽입하는 메써드이다.
  • List와 Set과는 다르게 put을 활용한다.
  • 이미 Key값이 Map안에 존재한다면, Value값을 덮어쓴다.
  • 만약, Key값이 Map에 존재하지 않는다면, 반환 값이 null, 이미 존재 한다면, 반환 값은 그 전에 존재하던 value값이다.
HashMap<Integer, String> hashMap = new HashMap<>();

System.out.println(hashMap.put(1, "first"));
// Map안의 원소: (1, "first")
// 출력 값: null (처음 삽입하기 때문)

System.out.println(hashMap.put(1, "second"));
// Map안의 원소: (1, "second") (덮어쓰기 때문)
// 출력 값: first (Key에 매핑되는 이전 Value를 출력)

System.out.println(hashMap.put(1, "third"));
// Map안의 원소: (1, "third") (덮어쓰기 때문)
// 출력 값: second (Key에 매핑되는 이전 Value를 출력)

  1. remove(Object Key)
  • 해당 키에 해당하는 데이터를 삭제한다.
  • 만약 해당 Key에 대한 데이터가 존재하지 않는다면 null, 존재한다면 그에 상응하는 Value값을 반환한다.
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");

// 존재하는 Key에 대한 데이터 제거
System.out.println(hashMap.remove(1));
// 출력 값: first (Key값 1에 대한 Value값이 first이므로)

// 존재하지 않는 Key에 대한 데이터 제거 시도
System.out.println(hashMap.remove(10));
// 출력 값: null (Key값 10에 대한 데이터가 없으므로)

  1. replace(K key, V oldValue, V newValue)
  • 해당 키에 해당하는 value값을 업데이트한다.
  • put을 통해서도 업데이트를 진행할 수 있지만, put은 데이터가 Map안에 없을 경우 삽입하기 떄문에, 업데이트가 목적이라면 안전하게 replace를 쓰는 것을 고려해볼만 하다.
  • Key에 대한 데이터가 이미 Map안에 존재하여, replace에 성공하면 true, 해당하는 Key에 대한 데이터가 없을 때는 false를 반환한다.
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");
// Map안의 원소: (1, "first")

hashMap.replace(1, "first", "newFirst");
// Map안의 원소: (1, "newFirst")

  1. get(Object key)
  • Key에 해당하는 Value를 얻고 싶을 때 사용한다.
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");

System.out.println(hashMap.get(1));
// 출력 값: first

  1. containsKey(Object key)
  • Map안에 해당 Key가 있는지 알 수 있다.
  • Key가 존재하면 true, 존재하지 않으면 false를 반환한다.
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");

System.out.println(hashMap.containsKey(1));
// 출력 값: true

System.out.println(hashMap.containsKey(2));
// 출력 값: false;

  1. containsValue(Object key)
  • Map안에 해당 Value가 있는지 알 수 있다.
  • Value가 존재하면 true, 존재하지 않으면 false를 반환한다.
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");

System.out.println(hashMap.containsValue("first"));
// 출력 값: true

System.out.println(hashMap.containsValue("second"));
// 출력 값: false;

  1. entrySet()
  • Map에 있는 mapping<Key, Value>을 Set으로 반환한다.
  • 반환 타입: Set<Map.Entry<K, V>>
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");
hashMap.put(2, "second");
hashMap.put(3, "third");

Set<Map.Entry<Integer, String>> entries = hashMap.entrySet();
// Map.Entry<Integer, String>으로 <Key, Value>를 받는다.

entries.forEach(i -> System.out.println("Key: " + i.getKey() + " Value: " + i.getValue()));
// 출력 값
// Key: 1 Value: first
// Key: 2 Value: second
// Key: 3 Value: third

  1. keySet()
  • Map에 있는 Key들을 얻을 수 있다.
  • 반환 타입은 Key들이 저장되어 있는 Set이다.
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");
hashMap.put(2, "second");
hashMap.put(3, "third");

Set<Integer> keySet = hashMap.keySet();
// Set으로 Key를 받는다.

keySet.forEach(i -> {
                System.out.println("Key: " + i);
});
// 출력 값
// Key: 1
// Key: 2
// Key: 3

  1. values()
  • Map에 있는 Value들을 얻을 수 있다.
  • Collection type으로 반환한다.
HashMap<Integer, String> hashMap = new HashMap<>();

hashMap.put(1, "first");
hashMap.put(2, "second");
hashMap.put(3, "third");

Collection<String> values = hashMap.values();
// Collection type으로 value를 받는다.

values.forEach(i ->
                System.out.println("Value: " + i));
// 출력 값
// Value: first
// Value: second
// Value: third

[ 참고 문헌 ]

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

https://tomining.tistory.com/168

https://www.delftstack.com/ko/howto/java/update-value-in-hashmap-java/