AdSense

網頁

2019/5/4

Java 如何遍歷(迴圈)Map

Java 對Map做迴圈(loop)的寫法如下。

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Main {

    public static void main(String[] args) {
        
        Map<Integer, String> map = createMap();
        
        // loop key
        for (Integer key : map.keySet()) {
            System.out.println(key);
        }
        printline();
        
        // loop value
        for (String value : map.values()) {
            System.out.println(value);
        }
        printline();
        
        // loop key:value
        for (Integer key : map.keySet()) {
            System.out.println(key + ":" + map.get(key));
        }
        printline();
        
        // loop key:value <-- 常用
        for (Entry<Integer, String> e : map.entrySet()) {
            System.out.println(e.getKey() + ":" + e.getValue());
        }
        printline();
        
        // Java 8 lambda expressoin
        map.forEach((key, value) -> System.out.println(key + ":" + value));
        
    }
    
    /** 建立一個Map物件,塞一些資料 */
    private static Map<Integer, String> createMap() {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Matt");
        map.put(2, "John");
        map.put(3, "Terry");
        map.put(4, "Mary");
        map.put(5, "Amy");
        return map;
    }
    /** 劃線 */
    private static void printline() {
        System.out.println("========================");
    }

}

印出結果如下。

1
2
3
4
5
========================
Matt
John
Terry
Mary
Amy
========================
1:Matt
2:John
3:Terry
4:Mary
5:Amy
========================
1:Matt
2:John
3:Terry
4:Mary
5:Amy
========================
1:Matt
2:John
3:Terry
4:Mary
5:Amy


參考:

沒有留言:

AdSense