[java] Map 반복(Iteration)시키는 3가지 방법 [펌]
[java] Map 반복(Iteration)시키는 3가지 방법 [펌]
이 세가지 방법 말고도 뭐 다른 방법이 있겠지만 대충 요 3가지 정도만 알고 있어도 충분하고도 넘칠것 같다.
이전까지는 제일 첫번째 방법으로만 Map 에 있는 것들을 꺼내서 썼었는데
세번째 방법도 꽤 간결하고 가독성도 좋은것 같아 앞으로 세번째 방법을 주로 써야 겠다는 생각을 해본다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.tistory.stove99;
import java.util.HashMap; import java.util.Iterator; import java.util.Map;
public class MapIterationSample { public static void main(String[] agrs) { Map<String, String> map = new HashMap<String, String>();
map.put("키1", "값1"); map.put("키2", "값2"); map.put("키3", "값3"); map.put("키4", "값4"); map.put("키5", "값5"); map.put("키6", "값6");
// 방법1 Iterator<String> keys = map.keySet().iterator(); while( keys.hasNext() ){ String key = keys.next(); System.out.println( String.format("키 : %s, 값 : %s", key, map.get(key)) ); }
// 방법2 for( Map.Entry<String, String> elem : map.entrySet() ){ System.out.println( String.format("키 : %s, 값 : %s", elem.getKey(), elem.getValue()) ); }
// 방법3 for( String key : map.keySet() ){ System.out.println( String.format("키 : %s, 값 : %s", key, map.get(key)) ); } } } |
출처: https://stove99.tistory.com/96 [스토브 훌로구]