You are a developer, not a coder.

Java Map 반복(Iteration)시키는 3가지 방법 본문

Backend-Languages/Java

Java Map 반복(Iteration)시키는 3가지 방법

Mattmk 2023. 5. 18. 13:37
SMALL
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)) );
        }
    }
}

 

LIST

'Backend-Languages > Java' 카테고리의 다른 글

Collection의 종류와 이해  (0) 2023.05.18
String, StringBuffer, StringBuilder에 대해서  (0) 2023.05.18
subList 알맞게 사용하는 방법  (0) 2021.02.24
COLLECTIONS.EMPTY_LIST  (0) 2020.12.15
JSON Pasing Tip  (0) 2020.12.01
Comments