코딩이란 무엇일까

Java/자바[16일차]Map컬렉션 본문

국비지원수업

Java/자바[16일차]Map컬렉션

둥구는 지굴다 2022. 11. 10. 21:26
☠️글을 읽기 전 필자는 아직 코딩을 배우는 단계이므로 글의 내용이 부정확할 수 있습니다.

여러 가지 글과 책, 수업을 바탕으로 정리한 내용이니 알맞지 않은 내용이 있다면 댓글 남겨주시면 수정하겠습니다.

Map이란?

Map은 컬렉션 프레임의 컬렉션이며

키(Key)와 값(Value)으로 구성된 Map.Entry객체를 저장하는 구조를 가지고 있습니다.

여기서 키와 값은 모두 객체입니다.

키는 Set과 마찬가지로 중복 저장이 안 되지만 값은 중복 저장할 수 있습니다.

만약 기존에 저장된 키와 동일한 키 값을 저장하면 기존의 값은 없어지며 새로운 값으로 대체합니다.

Map의 종류

Map컬렉션은 HashMap, Hashtable, LinkedHashMap, Properties, TreeMap 등이 있습니다.

Map컬렉션의 메서드

 

메서드  설명
boolean contiansKey(Object Key) 해당 키가 있는지 여부 반환
boolean containsValue(Object Value) 해당 값이 있는지 여부 반환
V get(Object Key) 해당 Key와 쌍인 값을 반환
isEmpty( ) 맵 객체에 요소가 없으면 true반환
Set<Key> KeySet( ) 키들을 Set 형태로 반환
V put(k Key, V value) 키와 값을 요소로 추가
V remove(Object Key) 이 키를 가진 요소를 제거
int size( ) 전체 요소의 개수를 반환

HashMap

HashMap은 Map인터페이스를 구현한 대표적인 Map컬렉션입니다.

HashMap 선언 방법

Map<K, V> map = new HashMap<K , V>( );

위에서 K는 키의 타입을 말하며 V는 값의 타입을 말합니다.

 

키를 String타입, 값을 Integer타입으로 선언할 때

Map<String , Integer> map= new HashMap<String,Integer>( );
Map<String , Integer> map= new HashMap( );

HashMap의 파라미터를 생략하면 Map의 지정된 타입을 따라갑니다.

HashMap 사용해보기

HashMap객체 생성

public static void main(String[] args) {
		
		//HashMap 객체 생성
		Map<String,String> map=new HashMap<>();
}

put( ) 메서드 사용하여 객체 추가하기

//put( ) => 객체 추가 메서드
		map.put("apple", "사과");
		map.put("banana", "바나나");
		map.put("grape", "포도");
		map.put("potato", "감자");
		map.put("soccer", "축구");

size( ) => HashMap 크기 반환 메서드

System.out.println(map.size()); //출력 결과:5

get( ) => 객체의 Value를 Key로 가져오기

		System.out.println(map.get("apple"));//결과 : 사과
		System.out.println(map.get("banana")); //결과 : 바나나
		System.out.println(map.get("grape")); //결과 : 포도
		System.out.println(map.get("potato"));//결과 : 감자
		System.out.println(map.get("soccer"));//결과 : 축구

객체 출력해보기

		//객체 출력해보기
		//toString( )메서드 생략가능
		System.out.println(map.toString());
		System.out.println(map);

출력 결과

remove( ) => Key로 value 삭제하기

//remove( ) => Key로 value삭제하기
		map.remove("apple");
		map.remove("grape");
		//Key와 Value값 모두 일치하는 것 삭제
		map.remove("potato","감자");

삭제된 HashMap확인

apple, grape, potato가 삭제되었다.

contains( ) ⇒ Key 혹은 Value를 인자로 넣어 해당 Key, Value가 있는지 true/false로 반환

//contains( ) => Key를 인자 값으로 받아 해당 Key가 있는지 true/false로 반환
		System.out.println(map.containsKey("apple")); //false
		System.out.println(map.containsKey("soccer")); //true
		//contains( ) => Value를 인자 값으로 받아 해당 Value가 있는지 true/false로 반환
		System.out.println(map.containsKey("사과")); //false
		System.out.println(map.containsValue("축구")); //true

Map에 저장된 전체 데이터 요소 출력 방법

Key값만 추출해서 Set을 만들고 Key를 이용하기

  1. Key를 추출하는 Set의 메서드는 KeySet( )
			Set<String> keyset=map.keySet();
				for(String s:keyset) {
					System.out.println("key값=>"+s+"\\tValue=>"+map.get(s));
				}

출력 결과

2.Map에서 Key와 Value를 entry라고 합니다. 따라서 이 entry를 set에 저장하는 메서드인 entrySet( ) 메서드를 사용합니다.

			//Map에 중첩된 Entry인터페이스 
			//사용할 수 있는 메서드 getKey( ): Key값을 가져올 수 있다.
			//getValue( ): Value 값을 가져올 수 있다.
			for(Map.Entry<String, String> s:map.entrySet()) 
			System.out.println("Key =>"+s.getKey()+"\\tValue =>"+s.getValue());
Comments