자료구조 - HashMap과 HashSet

itonse·2024년 4월 30일

HashMap

1. 선언

HashMap<String, Integer> map = new HashMap<>(); // <key, value> 형태

2. put 메서드 (값 추가)

map.put("초록", 1);
map.put("파랑", 2);

3. get 메서드 (key값의 value 얻기)

System.out.println(map.get("초록")); // 1

4. key 값 제거

map.remove("초록); // key값 "초록" 제거

5. 모든 key 값 제거

map.clear();

6. getOrDefault 메서드

map.put("노랑", map.getOrDefault("노랑", 0) + 1); // 키가 존재하지 않을 때 설정한 값(0)으로 반환

7. entrySet, keySet

  • HashMap의 두 가지 주요 순회 방법
  • entrySet(): 모든 키-값 쌍을 'Entry' 객체의 집합으로 반환
for (Entry<String, Integer> entry : map.entrySet()) {
	System.out.pringln("[Key]:" + entry.getKey() + "[Value]:" + entry.getValue());
}

// 출력 예
[key]:초록 [Value]: 1
[key]:파랑 [Value]: 2
[key]:노랑 [Value]: 3
  • keySet(): 맵의 모든 키를 Set 형태로 반환
for (String key : map.keySet()) {
	System.out.println("[Key]: + key + " [Value]:" + map.get(key));
}

// 출력 예
[key]:초록 [Value]: 1
[key]:파랑 [Value]: 2
[key]:노랑 [Value]: 3

HashMap 정렬

Collections.sort(keySet); // 키 값 기준 오름차순 정렬
Collections.reverse(keySet); // 키 값 기준 내림차순 정렬



HashSet

1. 선언

HashSet<Integer> set = new HashSet<>();

2. 데이터 넣기

set.add(1) // 1 넣기

3. 데이터 제거하기

set.remove(1) // 1 제거

4. HashSet에 해당 데이터가 있는지 확인

set.contains(1) // 1이 들어있는지 확인


HashMap과 HashSet 공통점

  • 데이터의 순서는 고려하지 않는다
  • 삽입, 삭제, 탐색 등 모든 함수의 시간복잡도가 전부 O(1)이다.


ref.
Java 코딩 테스트 준비 - HashMap과 HashSet
[자료구조/JAVA]HashMap이란?
https://ethereal-coder.tistory.com/153

0개의 댓글