Java/컬렉션

[Java]HashMap 키와 값을 가져오는 방법

DevStory 2022. 4. 4.

HashMap

HashMap 클래스는 키(Key)-값(Value) 쌍을 저장할 수 있는 Java의 컬렉션입니다. 키는 Map의 값을 연결하는데 사용되는 고유한 식별자로 중복되지 않습니다.

 

이번 포스팅은 Java의 Map 객체에서 키와 값을 가져오는 몇 가지 방법들을 소개합니다.


HashMap의 특징

HashMap에서 키와 값을 가져오는 방법을 소개하기 전에 HashMap의 특징들을 기억할 필요가 있습니다.

1. 키는 고유하므로 중복되지 않습니다.
2. 키는 Null이 될 수 있습니다.
3. HashMap은 Insert 순서를 보장하지 않습니다.

다음은 HashMap 객체 예제입니다.

Map<String, Integer> map = new HashMap<>();
map.put("John", 34);
map.put("Jane", 26);
map.put("Billy", null);
map.put(null, 3);

키와 값 가져오기

키와 값 모두 가져와야하는 경우 entrySet() 메서드 또는 forEach() 문을 사용합니다.


entrySet() 메서드

키와 값 모두 중요한 정보입니다. 키와 값을 같이 가져와야하는 경우 Map.Entry<K, V> 인터페이스의 entrySet() 메서드를 사용합니다. Map.Entry 인터페이스는 Map 객체의 키와 값을 접근할 수 있도록 해주는 getKey(), getValue() 함수가 존재합니다.

 

다음 예제는 Map.Entry 인터페이스로 Map 객체의 각 요소를 접근하고 entrySet() 메서드로 키와 값을 추출합니다.

Map<String, Integer> map = new HashMap<>();
map.put("John", 34);
map.put("Jane", 26);
map.put("Billy", null);
map.put(null, 3);

for (Map.Entry<String, Integer> pair : map.entrySet()) {
  System.out.println(String.format("Key (name) is: %s, Value (age) is : %s", pair.getKey(), pair.getValue()));
}

실행 결과

Key (name) is: null, Value (age) is : 3
Key (name) is: Billy, Value (age) is : null
Key (name) is: John, Value (age) is : 34
Key (name) is: Jane, Value (age) is : 26
반응형

forEach()문을 사용하여 키와 값 가져오기

객체를 순회하는 Iterator 객체를 생성하여 각 요소를 접근합니다.

Map<String, Integer> map = new HashMap<>();
map.put("John", 34);
map.put("Jane", 26);
map.put("Billy", null);
map.put(null, 3);

Iterator<Map.Entry<String, Integer>> itr = map.entrySet().iterator();

while(itr.hasNext())
{
  Map.Entry<String, Integer> entry = itr.next();
  System.out.println(String.format("Key (name) is: %s, Value (age) is : %s", entry.getKey(), entry.getValue()));
}

실행 결과

Key (name) is: null, Value (age) is : 3
Key (name) is: Billy, Value (age) is : null
Key (name) is: John, Value (age) is : 34
Key (name) is: Jane, Value (age) is : 26

 

Java 8을 사용하는 경우 forEach() 문과 람다식을 함께 사용하여 코드를 더 간결하게 작성할 수 있습니다. 

Map<String, Integer> map = new HashMap<>();
map.put("John", 34);
map.put("Jane", 26);
map.put("Billy", null);
map.put(null, 3);

map.forEach((k,v) -> System.out.println(String.format("Key (name) is: %s, Value (age) is : %s", k, v)));

실행 결과는 위 예제와 동일합니다.


키 가져오기

키만 가져오고 싶은 경우 keySet() 메서드를 사용합니다.

for (String key : map.keySet()) {
  System.out.println(key);
}

값 가져오기

값만 가져오고 싶은 경우 values() 메서드를 사용합니다.

for (String key : map.values()) {
  System.out.println(key);
}

특정 키가 존재하는지 확인 

특정 키가 존재하는지 체크하고 싶다면 containsKey() 메서드를 사용합니다. 키가 존재하면 true 그렇지 않으면 false가 반환됩니다.

boolean result = map.containsKey("Jane");
System.out.println(result);
반응형

댓글