/ JAVAJUNGSUK

Ch11-48~51. HashMap

자바의 정석 기초편

0. 목차



Chapter11. 컬렉션 프레임웍

Ch11 - 48. HashMap의 메서드

Ch11 - 49. HashMap 예제1

Ch11 - 50. HashMap 예제2

Ch11 - 51. HashMap 예제3



Ch11 - 48. HashMap의 메서드


▶ 생성자

▷ HashMap()
  • 배열 초기 용량 설정 가능
▷ HashMap(int initialCapacity)
▷ HashMap(int initialCapacity, float loadFactor)
▷ HashMap(Map m)
  • 다른 Map을 HashMap으로

▶ 저장

▷ Object put(Object key, Object value)
Object put("myId", "1111")

// put()으로 저장시키면, 아래와 같은 모양
[key]-[value]
[myId]-[1111]
▷ void put(Map m)
  • 지정 된 Map(m) 저장

▶ 삭제

▷ Object remove(Object key)
  • 지정 된 [key]-value 삭제

▶ 변경

▷ Object replace(Object key, Object value)
  • 새로운 key-value로 변경
▷ boolean replace(Object key, Object oldValue, Object newValue)


▶ 읽기

▷ Set entrySet()
  • Entry : key-value 쌍을 얻음
▷ Set keySet()
  • key만 얻음
▷ Set entrySet()
  • value만 얻음

▶ 내용 반환

▷ Object get(Object key)
  • key의 내용을 반환
      Object put("myId", "1111")
        
      "myId" 반환
    
▷ Object getOrDefault(Object key, Object defaultValue)
  • key의 내용이 없을 때, defaultValue를 반환

▶ check

▷ boolean containsKey(Object key)
  • key 존재 여부 확인
▷ boolean containsValue(Object value)
  • value 존재 여부 확인

▶ 기타

▷ int size()
  • 크기
▷ boolean isEmpty()
  • 공실 여부
▷ void clear()
  • 다 삭제
▷ Object clone()
  • 복제



Ch11 - 49. HashMap 예제1


▶ 로그인 - ID, PASSWORD

▷ 아이디, 패스워드 HashMap에 넣기 : put()
HashMap map = new HashMap();

map.put("aaaa", "1111");
map.put("bbbb", "2222");
map.put("bbbb", "3333");

// console
map : {aaaa=1111, bbbb=3333}

// 들어가 있는 모습
[key]-[value]
[aaaa]-[1111]
[bbbb]-[2222] -덮어쓰기→ [3333]
▷ 화면으로부터 입력받기 : Scanner()
Scanner s = new Scanner(System.in);
▷ id-pwd 일치 할 때까지 돌리기 : while(true)
while(true) {

}
▷ id, pwd 화면에서 입력받기 : scanner.nextLine()
while (true) {
  System.out.print("ID> ");
  String inputId = s.nextLine().trim();
  
  System.out.print("PASSWORD> ");
  String inputPassword = s.nextLine().trim();
}

// console
ID> aaaa
ID> bbbb
ID> cccc
ID> dddd
ID> 
▷ inputID가 없으면 에러 메세지 출력 : containsKey()
if (!map.containsKey(inputId)) System.out.println("NO_ID");
▷ inputID와 inputPassword가 불일치하면 에러 메세지 출력 : get(), equals()
else if (!(map.get(inputId)).equals(inputPassword)) System.out.println("MISMATCH!");
▷ inputID와 inputPassword가 일치하면 무한 반복문을 빠져나옴 : break;
else {
System.out.println("SUCCESS");
break;
}
package baek;

import java.util.HashMap;
import java.util.Scanner;

public class PlayHashMap {

	public static void main(String[] args) {
		
		HashMap map = new HashMap();
		
		map.put("aaaa", "1111");
		map.put("bbbb", "2222");
		map.put("bbbb", "3333");
		
		Scanner s = new Scanner(System.in);
		
		while (true) {
			System.out.print("ID> ");
			String inputId = s.nextLine().trim();

			System.out.print("PASSWORD> ");
			String inputPassword = s.nextLine().trim();
			
			if (!map.containsKey(inputId)) System.out.printf("\n---NO_ID---\n\n");
			
			else if (!(map.get(inputId)).equals(inputPassword)) System.out.printf("\n---ID_PASSWORD : MISMATCH!---\n\n");
			
			else {
				System.out.printf("\n---SUCCESS---");
				break;
			}
		}	
	}
}

// console
ID> aaaa
PASSWORD> aaaa

---ID_PASSWORD : MISMATCH!---

ID> cccc
PASSWORD> cccc

---NO_ID---

ID> aaaa
PASSWORD> 1111

---SUCCESS---



Ch11 - 49. HashMap 예제2


▶ 성적 관리

▷ 이름, 성적 HashMap에 넣기 : put()
HashMap map = new HashMap();

map.put("baek", new Integer(99));
map.put("baek", new Integer(100));
map.put("kim", new Integer(85));
map.put("oh", new Integer(77));
map.put("mark", new Integer(20));
map.put("luke", new Integer(86));
map.put("pavel", new Integer(96));

// console
map : {luke=86, pavel=96, oh=77, baek=100, kim=85, mark=20}

// 들어가 있는 모습
[key]-[value]
[baek]-[99] -덮어쓰기→ [100]
[kim]-[85] 
[oh]-[77] 
[mark]-[20] 
[luke]-[86] 
[pavel]-[96] 
▷ HashMap의 entry(key-value)를 가져와서 읽기 : entrySet(), iterator()
Set set = map.entrySet();
Iterator it = set.iterator();

while (it.hasNext()) {
  System.out.println(it.next());
}

// console
luke=86
pavel=96
oh=77
baek=100
kim=85
mark=20
▷ HashMap의 key(name) 가져와서 읽기 : keySet(), iterator()
set = map.keySet();
System.out.println("name : " + set);
▷ HashMap의 value(score) 가져와서 total 계산 : values(), iterator()
Collection value = map.values();
it = value.iterator();

int total = 0;

while(it.hasNext()) {
  int i = (int)it.next();
  total += i;
}
▷ HashMap의 value(score) 가져와서 average 계산 : (float)total/set.size()
float average = (float)total/set.size();

Comparable max = Collections.max(value);
Comparable min = Collections.min(value);
▷ HashMap의 value(score) 가져와서 max 계산 : Collections.max(value)
Comparable max = Collections.max(value);
▷ HashMap의 value(score) 가져와서 min 계산 : Collections.min(values)
Comparable min = Collections.min(value);
▷ 전체
package baek;

public class PlayHashMap2 {

	public static void main(String[] args) {
		
		HashMap map = new HashMap();
		
		map.put("baek", new Integer(99));
		map.put("baek", new Integer(100));
		map.put("kim", new Integer(85));
		map.put("oh", new Integer(77));
		map.put("mark", new Integer(20));
		map.put("luke", new Integer(86));
		map.put("pavel", new Integer(96));
		
		Set set = map.entrySet();
		Iterator it = set.iterator();
		
		while (it.hasNext()) {
			System.out.println(it.next());
		}
		
		set = map.keySet();
		System.out.println("name : " + set);

		Collection value = map.values();
		it = value.iterator();

		int total = 0;
		
		while(it.hasNext()) {
			int i = (int)it.next();
			total += i;
		}
		
		float average = (float)total/set.size();
		Comparable max = Collections.max(value);
		Comparable min = Collections.min(value);

		System.out.println("total : " + total);
		System.out.println("average : " + average);
		System.out.println("max : " + max);
		System.out.println("min : " + min);
	}
}

// console
luke=86
pavel=96
oh=77
baek=100
kim=85
mark=20
name : [luke, pavel, oh, baek, kim, mark]
total : 464
average : 77.333336
max : 100
min : 20



Ch11 - 49. HashMap 예제3


▶ 빈도수 계산

▷ data 넣기 : String[]
String[] data = {"Korea", "Korea", "Chezh", "USA", "UK", "Chezh", "Vietnam", "Korea",
                "Korea", "Korea", "Chezh", "UK", "German", "Chezh", "Korea", "USA",};
▷ map [data[n]]-[data[n]의 개수] 찍어 줄 for문 생성
for (int i = 0; i < data.length; i++) {

}
▷ map [data[n]]-[data[n]의 개수] : containsKey(), put(key, value)
for (int i = 0; i < data.length; i++) {
  if (map.containsKey(data[i])) { // map에 data[i]가 있으면
    int value = (int)map.get(data[i]); // data[i]의 value = int
    map.put(data[i], value + 1); // data[i]의 value에서 + 1, 빈도수 1 증가
    System.out.println(map);
  } else { // map에 data[i]가 없으면
    map.put(data[i], 1); // data[i]의 value = int 1
    System.out.println(map);
  }
}

// console
{Korea=1}
{Korea=2}
{Chezh=1, Korea=2}
{USA=1, Chezh=1, Korea=2}
{USA=1, UK=1, Chezh=1, Korea=2}
{USA=1, UK=1, Chezh=2, Korea=2}
{USA=1, Vietnam=1, UK=1, Chezh=2, Korea=2}
{USA=1, Vietnam=1, UK=1, Chezh=2, Korea=3}
{USA=1, Vietnam=1, UK=1, Chezh=2, Korea=4}
{USA=1, Vietnam=1, UK=1, Chezh=2, Korea=5}
{USA=1, Vietnam=1, UK=1, Chezh=3, Korea=5}
{USA=1, Vietnam=1, UK=2, Chezh=3, Korea=5}
{USA=1, Vietnam=1, UK=2, German=1, Chezh=3, Korea=5}
{USA=1, Vietnam=1, UK=2, German=1, Chezh=4, Korea=5}
{USA=1, Vietnam=1, UK=2, German=1, Chezh=4, Korea=6}
{USA=2, Vietnam=1, UK=2, German=1, Chezh=4, Korea=6}
▷ map의 entry 읽어오기 : entrySet(), iterator()
Iterator it = map.entrySet().iterator();
▷ 단어의 빈도수 출력
while (it.hasNext()) {
  Map.Entry entry = (Map.Entry)it.next();
  
  int value = (int)entry.getValue();
  
  System.out.println(entry.getKey() + " : " + value + "회");
}

// console
USA : 2
Vietnam : 1
UK : 2
German : 1
Chezh : 4
Korea : 6
▷ 기호로 빈도수만큼 표현
public static String printBar(char c, int value) {
  char[] bar = new char[value];
  
  for (int i = 0; i < bar.length; i++) {
    bar[i] = c;
  }
  return new String(bar);
}
while (it.hasNext()) {
  Map.Entry entry = (Map.Entry)it.next();
  
  int value = (int)entry.getValue();
  
  System.out.println(printBar('♡', value) + " -♡×" + value + "- " + entry.getKey());
}

// console
♡♡ -♡×2- USA
 -♡×1- Vietnam
♡♡ -♡×2- UK
 -♡×1- German
♡♡♡♡ -♡×4- Chezh
♡♡♡♡♡♡ -♡×6- Korea
▷ 전체
package baek;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class PlayHashMap3 {
	public static void main(String[] args) {
		String[] data = {"Korea", "Korea", "Chezh", "USA", "UK", "Chezh", "Vietnam", "Korea",
				"Korea", "Korea", "Chezh", "UK", "German", "Chezh", "Korea", "USA",};
		
		HashMap map = new HashMap();
		
		for (int i = 0; i < data.length; i++) {
			if (map.containsKey(data[i])) {
				int value = (int)map.get(data[i]);
				map.put(data[i], value + 1);
			} else {
				map.put(data[i], 1);
			}
		}
		
		Iterator it = map.entrySet().iterator();
		
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			
			int value = (int)entry.getValue();
			
			System.out.println(printBar('♡', value) + " -♡×" + value + "- " + entry.getKey());
		}
	}
		
	public static String printBar(char c, int value) {
		char[] bar = new char[value];
		
		for (int i = 0; i < bar.length; i++) {
			bar[i] = c;
		}
		
		return new String(bar);
	}
}

// console
♡♡ -♡×2- USA
 -♡×1- Vietnam
♡♡ -♡×2- UK
 -♡×1- German
♡♡♡♡ -♡×4- Chezh
♡♡♡♡♡♡ -♡×6- Korea