Java loop a map

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapDemo {
    public static void main(String[] args) {
        Map month  = new HashMap<>();
        month.put("First Month", "Jan");
        month.put("Second Month", "Feb");
        month.put("Third Month", "Mar");

        // Classic
        for (Map.Entry entry : month.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
        System.out.println("------------------------");

        // For fun
        Iterator> it = month.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = it.next();
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
        System.out.println("------------------------");

        // For each
        month.forEach((k, v) -> System.out.println(k + ", " + v));
        System.out.println("------------------------");

    }
}
Third Month, Mar
Second Month, Feb
First Month, Jan
------------------------
Third Month, Mar
Second Month, Feb
First Month, Jan
------------------------
Third Month, Mar
Second Month, Feb
First Month, Jan
------------------------

你可能感兴趣的:(Java loop a map)