Java

[Java] Map의 메소드

grove1212 2025. 1. 29. 20:16

1. put(K key, V value)

키와 값을 맵에 넣어준다. 키가 존재하면 새 값으로 대체된다.
LinkedList와 달리 add 가 아니라 put이라는 점에 주의한다.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 50);
map.put("apple", 100);
map.put("orange",20);

2. get(Object key)

지정된 키에 대응하는 값을 반환한다. 없으면 null 반환

int price = map.get("apple"); //100

3. getOrDefault(Object key, V defaultValue)

지정된 키에 대응하는 값을 반환한다. 없으면 지정된 값 반환

int price = map.getOrDefault("banana", 0); //0

4. remove(Object key)

키와 그에 대응하는 값을 제거

map.remove("orange");

5. containsKey(Object key) : boolean

지정된 키가 존재하는지 여부를 반환

map.containsKey("apple"); //true

6. containsValue(Object value) : boolean

지정된 값이 존재하는지 여부를 반환

boolean hasPrice100 = map.containsValue(100); //true

7. keySet()

Map에 모든 키를 담은 Set을 반환한다. 1번의 키가 존재하면 새로운 값으로 대체된다는 것 때문에 key는 무조건 중복되지 않는다.

// HashMap 준비        
Map<Integer, String> map = new HashMap<Integer, String>();        
map.put(1, "Apple");        
map.put(2, "Banana");        
map.put(3, "Orange");

// for loop (keySet())        
Set<Integer> keySet = map.keySet();        
for (Integer key : keySet) {            
System.out.println(key + " : " + map.get(key));        
}


// 결과
1 : Apple
2 : Banana
3 : Orange

8. value()

Map 내부의 모든 값을 담은 Collection을 반환한다.

  Map<Integer, String> map = new HashMap<Integer, String>();        
  map.put(1, "Apple");        
  map.put(2, "Banana");        
  map.put(3, "Orange");         

  Collection<String> values = map.values();        
  System.out.println(values);  // [Apple, Banana, Orange]

9. entrySet()

Map의 모든 키-값을 꺼내야 할 때

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
// 출력: apple: 50

10. size()

Map에 저장된 키-값 쌍의 개수를 반환

int size = map.size();

11. clear()

Map에 저장된 모든 것을 지울 때

map.clear();

12.putIfAbsent(K key, V value)

키에 대응하는 값이 없을 때만 키 - 값을 맵에 저장

13. replaceAll((BiFunction<? super K,? super V,? extends V> function))

모든 키-값 쌍에 대해 지정된 함수를 적용하여 값을 대체

map.replaceAll((key, value) -> value + 10);

14. replace(K key, V value)

지정된 key가 있으면 그에 대응하는 값으로 대체한다.

map.replace("apple", 20);

참고 링크
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
https://coding-daily.tistory.com/363