버글버글

Java 수업 기록 (19) Collection Framework - maping, treemap 본문

java/java 수업 기록

Java 수업 기록 (19) Collection Framework - maping, treemap

Bugle 2022. 8. 11. 00:00
반응형

▶ map(maping) 인터페이스 

▶ hash map 

1. 키(Key)와 값(Value)으로 하나의 Entry가 구성되는 자료 구조

2. 저장하려는 데이터는 값이고, 값을 알아내기 위해서 키를 사용

3. 값(Value)은 중복이 가능하지만 키(Key)는 중복이 불가능

4. 해시(Hash)를 이용하기 떄문에 삽입, 삭제, 검색이 빠름

* 압도적으로 많이 사용됨

K = key

V = value

java.util.Map;

Entry : Key, Value

* HashMap의 주요 메소드

메소드 역할
void clear() 모든 Entry 삭제
boolean containsKey(Object Key) 전달된 key를 포함하고 있으며 true 반환
boolean containsValue(Object value) 전달된 value를 포함하고 있으며 true 반환
Set<Map.Entry<K, V>> entrySet() 해시맵의 모든 Entry를 저장한 Set 반환
V get(Object key) 전달된 key의 값(value) 반환, 없으면 null 반환
boolean isEmpty() 해시맵이 비어 있으면 true 반환
Set<V> keySet() 해시맵의 모든 key를 저장한 Set 반환
V put(K key, V value) key와 value를 하나의 Entry로 해시맵에 저장하고 저장한 value를 반환
V remove(Object key) 전달된 key를 가진 Entry를 해시맵에서 삭제하고 삭제한 calue를 반환
int size() 전체 Entry 개수 반환

 

 

* 맵 생성

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

* 추가

- 새로운 key 값을 사용하면 추가.

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

		dictionary.put("apple", "사과");
		dictionary.put("banana", "바나나");
		dictionary.put("tomato", "토마토");
		dictionary.put("mango", "망고");
		dictionary.put("melon", "멜론");
        
		System.out.println(dictionary);
		// {banana=바나나, apple=사과, tomato=토마토, melon=멜론, mango=망고}

* Key값과 Value값은 한개의 데이터이다.

  - apple과 사과는 같은 데이터.

 

* 수정

- 기존의 key 값을 사용하면 수정

		Map<String, String> dictionary = new HashMap<String, String>();
		
		dictionary.put("melon", "멜론");
		
		System.out.println(dictionary);	// 멜론
		
		// 수정
		dictionary.put("melon", "메론");
		System.out.println(dictionary);	// 메론

* 삭제

- 삭제할 요소의 key를 전달하면 삭제

		Map<String, String> dictionary = new HashMap<String, String>();
		
		dictionary.put("tomato", "토마토");

		System.out.println(dictionary);	// {tomato=토마토}

		// 삭제
		String removeItem = dictionary.remove("tomato");
		System.out.println(removeItem);	// 토마토

* 값(Value) 확인

		Map<String, String> dictionary = new HashMap<String, String>();
		
		dictionary.put("apple", "사과");
		
		// 값(Value) 확인
		System.out.println(dictionary.get("apple"));	// 사과
		System.out.println(dictionary.get("peach"));	// null

- 실무에서 가장 많이 보이는 맵1 <String, Object>

- object는 모든 객체를 저장할 수 있다.

		Map<String, Object> map2 = new HashMap<String, Object>();

- 실무에서 가장 많이 보이는 맵2 <String, String>

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

* Entry 단위로 순회(for)

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title", "소나기");
		map.put("author", "황순원");
		map.put("price", 20000);
		
		for(Map.Entry<String, Object> entry : map.entrySet()) {
			System.out.println(entry.getKey() + ":" + entry.getValue());			
		}
        
		// author:황순원
		// price:20000
		// title:소나기

* Key를 이용한 순회(for)

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title", "소나기");
		map.put("author", "황순원");
		map.put("price", 20000);
		

		for(String key : map.keySet()) {
			System.out.println(key + ":" + map.get(key));
		}
                
		// author:황순원
		// price:20000
		// title:소나기

예제) title, author, price 정보를 가진 임의의 Map 3개를 만들고,생성된 Map 3개를 ArrayList에 저장한 뒤,  

          ArrayList에 저장된 Map 3개를 for문으로 순회하시오.

	public static void m4() {
    
		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("title", "소나기");
		map1.put("author", "황순원");
		map1.put("price", 20000);
		
		Map<String, Object> map2 = new HashMap<String, Object>();		
		map2.put("title", "어린왕자");
		map2.put("author", "생택쥐베리");
		map2.put("price", 10000 + "");
		
		Map<String, Object> map3 = new HashMap<String, Object>();		
		map3.put("title", "홍길동전");
		map3.put("author", "허균");
		map3.put("price", 30000);
		
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		list.add(map1);
		list.add(map2);
		list.add(map3);
		
		for(Map<String, Object> map : list) {	// List
			for(Map.Entry<String, Object> entry : map.entrySet()) {	// Map
				System.out.println(entry.getKey() + ":" + entry.getValue());
			}
			System.out.println();
		}

	}

 

 

▶ treemap 

* 자동으로 정렬이 되서 저장된다. (마인드 맵처럼 생겼지만 약간 다름)

* 안쓰임

▶ 이진 트리(binary tree) 

1. 모든 노드는 2개의 자식을 가질 수 있다.
2. 작은 값은 왼쪽, 큰 값은 오른쪽에 저장한다.

 

▶ treeMap 

1. key를 기준으로 왼쪽에 작은 값, 오른쪽에 큰 값이 저장된다.
2. key를 기준으로 자동으로 정렬되면서 저장된다.
3. 크기 비교 및 범위 연산에 적절하다

4. TreeMap은 TreeMap만 사용할 수 있는 메소드가 다수 있으므로, TreeMap 타입으로 생성하는 것이 좋다.

		Map<Integer, String> map = new TreeMap<Integer, String>();
		
		map.put(65, "제시카");
		map.put(85, "에밀리");
		map.put(35, "제임스");
		map.put(95, "사만다");
		
		System.out.println(map);
		// {35=제임스, 65=제시카, 85=에밀리, 95=사만다}

* for 순회

		Map<Integer, String> map = new TreeMap<Integer, String>();
		
		map.put(65, "제시카");
		map.put(85, "에밀리");
		map.put(35, "제임스");
		map.put(95, "사만다");
		
		// 순회
		for(Map.Entry<Integer, String> entry : map.entrySet()) {
			System.out.println(entry.getKey() + ":" + entry.getValue());
		}
		// 35:제임스
		// 65:제시카
		// 85:에밀리
		// 95:사만다

* 기본 정렬 = 오름차순 정렬

 - 정렬 변경 시 : decendingMap() 메소드 호출

 - 오름차순 정렬 ↔ 내림차순 정렬

		TreeMap<Integer, String> map = new TreeMap<Integer, String>();
		
		map.put(65, "제시카");
		map.put(85, "에밀리");
		map.put(35, "제임스");
		map.put(95, "사만다");
		
		NavigableMap<Integer, String> map2 = map.descendingMap();
		System.out.println(map2);

* 다시 decendingMap() 메소드를 호출하면 오름차순 정렬이 된다.

		NavigableMap<Integer, String> map3 = map2.descendingMap();
		for(Integer key : map3.keySet()) {
			System.out.println(key + ":" + map3.get(key));
		}

 

 

반응형