Java

[Java] HashMap 이란? HashMap 사용법과 예제

오늘보다 더 나은 내일을 위해 2021. 2. 1. 23:18

 

 

1. HashMap이란?

 

key와 value의 쌍으로 이루어진 데이터를 저장하는 구조로 이루어져 있습니다.

 

| 특징

  • <String : Integer>,  <String : String> 형태 모두 가능합니다.

  • 저장되는 key와 value는 null 값을 허용합니다.

  • 많은 양의 데이터를 검색 할때 뛰어난 성능을 보입니다.

 

2. 예제

 

1) HashMap 선언

import java.util.HashMap; 	

HashMap<String, String> hmap1 = new HashMap<String, String>();
HashMap<Integer, String> hmap2 = new HashMap<String, String>();
Map<String, String> hmap3 = new HashMap<>();	//new에서 타입 파라미터 생략가능
HashMap<String, String> hmap4 = new HashMap<>(10);	// 크기 지정해서 생성

 

2. 데이터 추가, put

Map<String, String> words = new HashMap<>();
// 값 추가
words.put("사과", "apple");
words.put("책", "book");
words.put("가방", "bag");
words.put("사진", "picture");
words.put("개", "dog");

 

3. 특정 key에 해당하는 value 가져오기, get

Map<String, String> words = new HashMap<>();

words.put("사과", "apple");
words.put("책", "book");
words.put("가방", "bag");
words.put("사진", "picture");
words.put("개", "dog");

System.out.println(words.get("개"));    // dog
System.out.println(words.get("카메라"));    // null 
// map에 없는 key는 null로 반환

 

4. 전체 출력하기

Map<String, String> words = new HashMap<>();

words.put("사과", "apple");
words.put("책", "book");
words.put("가방", "bag");
words.put("사진", "picture");
words.put("개", "dog");

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

System.out.println(" ");

for(Map.Entry<String, String> set : words.entrySet()){
System.out.println(set);
}

<결과>

picture
book
apple
bag
dog

사진=picture
책=book
사과=apple
가방=bag
개=dog

 

5. 특정 key/value를 포함하고 있는지 확인하기, containsKey / containsValue

Map<String, String> words = new HashMap<>();

words.put("사과", "apple");
words.put("책", "book");
words.put("가방", "bag");
words.put("사진", "picture");
words.put("개", "dog");

// map 안에 해당 key가 있는지 확인하는 메소드, boolean 타입으로 값을 반환한다
System.out.println(words.containsKey("책"));	// true
System.out.println(words.containsValue("apple"));	// true
System.out.println(words.containsValue("building"));	// false

 

6. value 바꾸기, replace

Map<String, String> words = new HashMap<>();

words.put("사과", "apple");
words.put("책", "book");
words.put("가방", "bag");
words.put("사진", "picture");
words.put("개", "dog");

System.out.println(words.get("사진"));	// picture

words.replace("사진", "photo");

System.out.println(words.get("사진"));	// photo