본문 바로가기
Java

[Java] Collections(2)_Map 인터페이스

by happyhelen 2021. 8. 24.

Map 컬렉션 클래스들은 '키: 값' 의 쌍으로 저장하는 방식이다

 

순서는 고려하지 않으며, 값의 중복은 가능하지만 키의 중복은 불가하다

 

대표적인 클래스는 HashMap, Hashtable, TreeMap 이 있고

 

선언 시 Map<> map = new HashMap<>(); 이런 식으로 Map 으로 객체 생성을 하지 않는 이유는

 

Map 은 인터페이스이기 때문에 Map 을 상속받은 자식클래스로 객체를 생성하기 때문이다

 

 

 

 

HashMap

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

public class No19_HashMap {

	public static void main(String[] args) {
		Map<String , Integer> hm = new HashMap<>();
		
		// [1] 요소저장
		hm.put("서울", 01);
		hm.put("경기", 02);
		hm.put("인천", 03);
		
		// [2] 키의 집합, 값의 집합 
		System.out.println(hm.keySet()); // 키 집합
		System.out.println(hm.values()); // 값 집합
		
		// [3] 키로 값찾기
		System.out.println(hm.get("서울")); // 01
		System.out.println(hm.get("부산")); // null
		
		// [4] iterator()을 사용해 출력
		Iterator<String> keys = hm.keySet().iterator();
		
		while(keys.hasNext()) {
			String s = keys.next();
			System.out.println(s + hm.get(s));
		}
		
		// [5] 요소 수정
		hm.replace("인천", 04);
	}

}

 

++ 추가

		// 키, 값 둘다순회 entrySet()
		for(Map.Entry<String ,Integer> m : hm.entrySet()) {
			System.out.println(m.getKey()+" : "+m.getValue());
		}
		
		// 최대 value값이 1개인경우
		System.out.println(Collections.max(hm.values()));
		
		// value값이 중복인 경우 key 최대값찾기
		String a = hm.entrySet().stream()
				.max((m1, m2) -> m1.getValue() > m2.getValue() ? 1 : -1)
				.get().getKey();
		System.out.println(a);