[java]Generic Collection의 활용 - HashMap

Yejun Jang·2022년 5월 8일
0

HashMap<K, V> 컬렉션은 경로명이 java.util.HashMap이며,
‘키(key)’와 ‘값(value)’의 쌍으로 구성된다.

K는 ‘키(key)’로 사용할 데이터 타입,
V는 ‘값(value)’으로 사용할 데이터 타입의 타입 매개 변수.

HashMap<String, String> h =
new HashMap<String, String>();
// HashMap 컬렉션 생성

h.put("apple", "사과");
// "apple" 키와 "사과" 값의 쌍을 h에 삽입

String kor = h.get("apple");
// "apple" 키의 값을 검색. kor는 "사과"

< HashMap 컬렉션의 주요 메소드 >

void clear() :
HashMap의 모든 요소 삭제

boolean containsKey(Object key) :
지정된 키(key)를 포함하고 있으면 true 리턴

boolean containsValue(Object value) :
하나 이상의 키를 지정된 값(value)에 매핑시킬 수
있으면 true 리턴

V get(Object key) :
지정된 키(key)에 매핑되는 값 리턴.
키에 매핑되는 어떤 값도 없으면 null 리턴

boolean isEmpty() :
HashMap이 비어 있으면 true 리턴

Set keySet() :
HashMap에 있는 모든 키를 담은 Set 컬렉션 리턴

V put(K key, V value) :
key와 value를 매핑하여 HashMap에 저장

V remove(Object key) :
지정된 키(key)와 이에 매핑된 값을 HashMap에서 삭제

int size() :
HashMap에 포함된 요소의 개수 리턴

<구현 절차>

  1. HashMap 생성 HashMap<String, String> h =
    new HashMap<String, String>();
  2. HashMap에 요소 삽입(put)과 가져오기(get) h.put("baby", "아기");
    h.put("love", "사랑");
    h.put("apple", "사과");

String kor1 = h.get("love");
// key값이 love인 value = "사랑" Thus, kor1 = "사랑"
String kor2 = h.get("apple");
// key값이 apple인 value = "사과" Thus, kor2 = "사과"

  1. ‘키’로 요소 삭제

    h.remove("apple");

  2. 요소 개수 알아내기

    int n = h.size();

  3. HashMap을 이용하여 영어 단어와 한글 단어를 같이
    저장하고 검색하는 예제 :

    public class HashMapDicEx {
    public static void main(String[] args) {

        HashMap<String, String> dic =

    new HashMap<String, String>();
    // 영단어와 한글 단어 저장하는 HashMap컬렉션 생성

        dic.put("baby", "아기");
        dic.put("love", "사랑");
        dic.put("apple", "사과");

    // 3개의 (key, value) 쌍을 dic에 저장

        Set<String> keys = dic.keySet(); 

    // key 문자열을 가진 집합 Set 컬렉션 리턴

        Iterator<String> it = keys.iterator(); 

    // key 문자열을 순서대로 접근가능한 Iterator 리턴

        while (it.hasNext()) {
            String key = it.next();
            String value = dic.get(key);
            System.out.println("(" + key + ", " 

    + value + ")");

        }// dic 컬렉션에 들어 있는 모든 (key, value) 출력
    
    
    
    
     // 사용자로부터 영단어를 입력받고 한글 단어 검색
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < 3; i++) {
            System.out.print("찾고 싶은 단어는? ");
            String eng = sc.next();
            System.out.println(dic.get(eng));
            // '키' eng에 해당하는 '값' 리턴
        }
    }

    }

    실행 결과 :

(love, 사랑)
(apple, 사과)
(baby, 아기)
찾고 싶은 단어는? apple
사과
찾고 싶은 단어는? love
사랑
찾고 싶은 단어는? baby
아기

public class HashMapScoreEx {
public static void main(String[] args) {
// 사용자 이름과 점수를 기록하는 HashMap컬렉션 생성
HashMap<String, Integer> javaScore =
new HashMap<String, Integer>();

    // 5개의 점수 저장
    javaScore.put("amy", 97);
    javaScore.put("jason", 34);
    javaScore.put("steve", 98);
    javaScore.put("matt", 70);
    javaScore.put("Tony", 99);

    System.out.println("HashMap의 요소 개수 : "

+ javaScore.size());

// 모든 사람의 점수 출력.
// javaScore에 들어 있는 모든 (key, value) 쌍 출력
Set keys = javaScore.keySet();
// key 문자열을 가진 집합 Set 컬렉션 리턴
Iterator it = keys.iterator();
// key 문자열을 순서대로 접근가능한 Iterator 리턴

    while (it.hasNext()) {
        String name = it.next();     

// 다음 키, 학생 이름
int score = javaScore.get(name);
// 점수 알아내기
System.out.println(name + " : " + score);
}
}
}

실행 결과 :

HashMap의 요소 개수 : 5
matt : 70
Tony : 99
amy : 97
steve : 98
jason : 34
// 출력된 결과와 삽입된 순서와 다르다!!

profile
자바 개발자

0개의 댓글