본문 바로가기
Develop/Ps

[Java] Map 메서드

by J-rain 2024. 4. 11.

 

HashMap

1. put(K key, V value)

키와 값을 맵에 저장 한다.

키가 존재하면 새값으로 대체된다.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 50);
map.put("banana", 30);

 

2.get(Object key)

지정된 키에 대응하는 값을 반환하다. 

키가 없으면 null을 반환

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

 

3.remove(Object key)

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

map.remove("banana");

 

4.cotainsKey(Object key)

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

boolean hasApple = map.containsKey("apple"); // true

 

5.containsValue(Object value)

Map에 해당 값이 존재하는 여부를 파악

boolean hasPrice50 = map.containsValue(50); // true

 

6. keySet()

Map에 모든 키를 담은 Set을 반환한다.

// 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> set = map.keySet();        
for (Integer key : set) {            
System.out.println(key + " : " + map.get(key));        
}


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

 

7.values()

Map에 모든 값을 담은 Collection을  반환한다.

  Map<Integer, String> map = new HashMap<Integer, String>();        
  map.put(1, "Apple");        
  map.put(2, "Banana");        
  map.put(3, "Orange");         
     
  Collection<String> vals = map.values();        
  System.out.println(vals);  // [Apple, Banana, Orange]

 

8. entrySet()

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

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

 

9.size()

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

int size = map.size(); // 1


10.clear()

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

map.clear();

 

11.getOrDefault(Object key, V defaultValue)

키에 대응 하는 값을 반환하고 키가 존재하지 않는다면 defaultValue 값을 반환

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

 

12.putIfAbsent(K key, V value)

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

map.putIfAbsent("apple", 60);

 

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

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

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

 

14.replace(k key, V value)

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

map.replace("apple", 70);

'Develop > Ps' 카테고리의 다른 글

[Java] Set 메서드  (0) 2024.04.15
[Java] List 메서드  (1) 2024.04.11
[C++] STL Priority_queue 사용법  (0) 2024.01.07
[C++] STL map 사용법  (0) 2023.12.24
[C++] STL lower_bound, upper_bound 사용법  (2) 2023.12.21

댓글