HashMap 특정 키가 존재하는지 확인하는 방법
이번 포스팅은 Java의 HashMap 객체에서 특정 키가 존재하는지 확인하는 방법을 소개합니다.
containsKey()
HashMap 클래스의 containsKey() 메서드를 사용하여 특정 키가 존재하는지 확인할 수 있습니다. 키가 존재하면 true를 반환하고 그렇지 않으면 false를 반환합니다.
다음 예제는 containsKey() 메서드 호출 방법입니다.
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// Null 존재하는지 체크
boolean isExistsNull = map.containsKey(null);
System.out.println("isExistsNull: " + isExistsNull);
// "One" 존재하는지 체크
boolean isExistsOne = map.containsKey("One");
System.out.println("isExistsOne: " + isExistsOne);
실행 결과
isExistsNull: false
isExistsOne: true
반복자(Iterator)
두 번째 방법으로 HashMap 객체의 키를 ArrayList 객체로 변환 후 반복자를 사용하여 특정 키가 존재하는지 확인할 수 있습니다.
다음 예제는 "One"이라는 키가 존재하는지 확인하는 예제입니다.
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
// HashMap 객체의 키를 ArrayList로 변환
ArrayList<String> keys = new ArrayList<>(map.keySet());
// ArrayList를 반복하기 위해 반복자 생성
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
// 키에 "One"이 있는지 체크
if(iterator.next().equals("One")) {
System.out.println("One은 존재합니다.");
}
}
실행 결과
One은 존재합니다.
반복자를 사용하는 방법은 한 가지 문제가 존재합니다. HashMap 객체의 키 또는 값에는 null이 포함될 수 있습니다. 따라서 HashMap 객체의 키에 null이 존재하는 경우 NullPointerException 예외가 발생합니다.
다음 예제는 HashMap 객체의 키에 null이 존재하는 경우입니다.
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.put(null, 4);
// HashMap 객체의 키를 ArrayList로 변환
ArrayList<String> keys = new ArrayList<>(map.keySet());
// ArrayList를 반복하기 위해 반복자 생성
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
// 키에 "One"이 있는지 체크
if(iterator.next().equals("One")) {
System.out.println("One은 존재합니다.");
}
}
실행 결과
Exception in thread "main" java.lang.NullPointerException
반복문
다음 예제는 HashMap 객체를 반복문으로 순회하여 키가 존재하는지 확인하는 방법입니다.
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
for(Map.Entry<String, Integer> entry: map.entrySet()) {
if(entry.getKey().equals("One")) {
System.out.println("One은 존재합니다.");
}
}
실행 결과
One은 존재합니다.
이 방법도 HashMap 객체의 키에 null이 존재하는 경우 NullPointerException 예외가 발생합니다.
정리
- HashMap에서 특정 키가 존재하는지 확인하는 방법으로 HashMap 클래스의 containsKey() 메서드, 반복자, 반복문이 존재합니다.
- 반복자와 반복문을 사용하는 방법은 HashMap 객체의 키에 null이 존재하는 경우 NullPointerException 예외가 발생합니다.
- HashMap 클래스의 containsKey() 메서드는 HashMap 객체의 키에 null이 존재하더라도 NullPointerException 예외가 발생하지 않습니다.
반응형
'Java > 컬렉션' 카테고리의 다른 글
[Java]ArrayList 다중 삭제 (0) | 2022.06.22 |
---|---|
[Java]ArrayList 초기화 방법 (0) | 2022.06.20 |
[Java]ArrayList 특정 값 삭제 (0) | 2022.05.30 |
[Java]두 개의 ArrayList 합치기(merge) (1) | 2022.05.30 |
[Java]ArrayList 모두 삭제 clear(), removeAll() (1) | 2022.05.27 |
댓글