Map

 

Map 인터페이스는 (Key, Value) 형태의 저장 방식을 사용한다.

Key의 경우는 값을 저장하고 가져오기 위한 유일한 열쇠이며, Value는 Key에 종속된 데이터이다.

Key는 중복을 허용하지 않으며, Value는 중복이 허용된다.

 

 

예제

 

public class MapEx {
 
    public static void main(String[] args) {
        
        // map<key : value> value의 자료형이 Object라 모든 Object는 다 들어갈수 있다.
        Map<String, Object> map = new HashMap<String, Object>();
        
        // Map에 문자열 데이터를 넣는다.
        map.put("testStr", "테스트 데이터 입니다.");
        
        // Map에 정수 데이터를 넣는다.
        map.put("testInt", 1234567890);
        
        System.out.println("문자열 데이터 표출 : " + map.get("testStr"));
        System.out.println("정수 데이터 표출 : " + map.get("testInt"));
        
        System.out.println("자료형 :: " + map.get("testStr").getClass().getName());
        System.out.println("자료형 :: " + map.get("testInt").getClass().getName());
        
        // map 데이터를 문자열에 셋팅
        String setStr = map.get("testStr").toString();
        
        // map 데이터를 int에 셋팅
        int setInt = (int)map.get("testInt");
        
    }
    
}

Map 인터페이스의 경우 HashMap<K,V>을 제일 많이 사용한다.

HashMap의 경우 Key, Value를 묶어 하나의 Entry형식으로 저장한다.

 

실행결과

 

 

 

HashMap의 사용법

 

1. 키, 값 저장(Put) / 읽기(Get)

import java.util.HashMap;
import java.util.Map;
public class Main {
	public static void main(String[] ar) {
		Map<String,Integer> map=new HashMap();	//<키 자료형, 값 자료형>
		map.put("A", 100);
		map.put("B", 101);
		map.put("C", 102);
		map.put("C", 103); //중복된 key가 들어갈때는 이전 키,값을 지금의 것으로 업데이트
		System.out.println(map);
		System.out.println(map.get("A"));
		System.out.println(map.get("B"));
		System.out.println(map.get("C"));
	}
}

 

결과

{A=100, B=101, C=103}
100
101
103

 

 

2. containKey (HashMap에 키가 이미 존재한다면 덮어쓰지 않음)

public static void main(String[] ar){
	Map<String,Integer> map=new HashMap();
	map.put("key1", 100);
	map.put("key2", 200);
	if(!map.containsKey("key2"))	//키가 들어있는지 확인. 있으면 덮어쓰지 않는다.
		map.put("key2", 300); 
	System.out.println(map);
	System.out.println(map.get("key1"));
	System.out.println(map.get("key2"));
}

 

결과

{key1=100, key2=200}
100
200

 

 

3. putAll (Map에 다른 Map을 전부 포함)

public static void main(String[] ar) {
	Map<String,Integer> map1=new HashMap();
	Map<String,Integer> map2=new HashMap();
	//map1 put
	map1.put("map1-key1", 100);
	map1.put("map1-key2", 200);
		
	//map2 put
	map2.put("map2-key3", 300);
	map2.put("map2-key4", 400);
		
	System.out.println("map1:"+map1);
	System.out.println("map2:"+map2);
		
	//map2에 map1을 합침
	map2.putAll(map1);
	System.out.println("map2 includes map1:"+map2);
		
	//map1의 키, 값 변경
	map1.put("map1-key1", 1000);
	//map2에는 영향 없음.
	System.out.println("map2 includes map1:"+map2);
}

 

결과

map1:{map1-key1=100, map1-key2=200}
map2:{map2-key4=400, map2-key3=300}
map2 includes map1:{map2-key4=400, map1-key1=100, map1-key2=200, map2-key3=300}
map2 includes map1:{map2-key4=400, map1-key1=100, map1-key2=200, map2-key3=300}

putAll 메소드를 사용할 때 주의해야 할 점은 반드시 Key와 Value의 자료형이 같은 Map이어야 한다.

다른 자료형의 Key, Value 는 받을 수 없다.

 

 

4. KeySet() (모든 키를 순회한다)

public static void main(String[] ar) {
	Map<String,Integer> map=new HashMap();
	map.put("key1",50);
	map.put("key2",100);
	map.put("key3",150);
	map.put("key4",200);
		
	System.out.println("All key-value pairs");
	for(String key:map.keySet()) {
		System.out.println("{"+key+","+map.get(key)+"}");
	}

}

 

결과

All key-value pairs
{key1,50}
{key2,100}
{key3,150}
{key4,200}

 

 

5. forEach() (람다식을 이용한 순환 - 람다말고도 forEach는 제이쿼리, 자바스크립트로도 사용가능)

public static void main(String[] ar) {
	Map<String,Integer> hm=new HashMap();
	hm.put("http",80);
	hm.put("ssh", 22);
	hm.put("dns", 53);
	hm.put("telnet",23);
	hm.put("ftp", 21);
	hm.forEach((key,value)->
	{
		System.out.println("{"+key+","+value+"}");
		
	});
	
}

 

결과

{ftp,21}
{telnet,23}
{dns,53}
{http,80}
{ssh,22}

 

 

 

출처 :

https://dion-ko.tistory.com/69

https://reakwon.tistory.com/151

+ Recent posts