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<String, String> month  = new HashMap<>();
        month.put("First Month", "Jan");
        month.put("Second Month", "Feb");
        month.put("Third Month", "Mar");

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

        // For fun
        Iterator<Map.Entry<String, String>> it = month.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> 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
------------------------
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容