Map의 값 추출

Map의 값을 추출할때의 메서드 방식에 대해서 소개한다.

1) .put( ) 메서드로 key, value값을 넣어준다

Map<String, Object> pmap = new HashMap<>( );
		
pmap.put("1", "dsg");
pmap.put("2", "kmb");
pmap.put("3", "ibk");
				
System.out.println("pmap : " + pmap);

.put( ) 메서드를 활용한 결과는 다음과 같다.

2) .keySet( ) , .values( ) , .entrySet( )

for(String key : pmap.keySet()) {			
	System.out.println(key);
}
		
for(String key : pmap.keySet()) {
	System.out.println(pmap.get(key));
}
		
for(Object value : pmap.values()) {	
	System.out.println(value);
}
		
for(Entry<String, Object> val : pmap.entrySet()) {
	System.out.println("key : " + val.getKey() + ", " + " val : " + val.getValue());
}

.keySet( ) 메서드로 HashMap의 key값만 가져올수 있으며
.value( ) 메서드로 HashMap의 value값만 가져올수있다.
HashMap에 저장된 key, value값을 entry형태로 set에 저장하여 반환할수도 있다.

결과는 다음과 같다.

3) forEach문 + .keySet( ) .values( ) .entrySet( )

pmap.entrySet()	
	.stream()
	.map(Entry::getValue)					
	.forEach(System.out::println);		
		
pmap.keySet()
	.forEach(System.out::println);
		
pmap.values()
	.forEach(System.out::println);

이때 '::' 는 메소드참조로써
클래스이름::메소드이름 or 참조변수이름::메소드이름
으로 쓰일수있다.

결과는 다음과 같다.

좋은 웹페이지 즐겨찾기