Java遍历Map集合的三种方法

package com.xqnode;

import java.util.*;

/** * 遍历map集合的三种方法 * Created by xiaqing on 2017/10/21. */
public class RunMain {
    public static void main(String[] args){
        System.out.println("Hello World!");
        Map<String,Object> map = new HashMap <>();
        map.put("a","a");
        map.put("b",1);
        map.put("c",false);
        //方法一
        Iterator <String> keyIterator = map.keySet().iterator();
        while(keyIterator.hasNext()){
            String key = keyIterator.next();
            Object value = map.get(key);
            System.out.println("key:"+key+",value:"+value);
        }
        //方法二
        Iterator <Map.Entry <String, Object>> entryIterator = map.entrySet().iterator();
        while (entryIterator.hasNext()){
            Map.Entry <String, Object> mapEntry = entryIterator.next();
            String key = mapEntry.getKey();
            Object value = mapEntry.getValue();
            System.out.println("key:"+key+",value:"+value);
        }
        //方法三
        Collection <Object> values = map.values();
        for (Object o: values) {
            System.out.println(o);
        }
    }
}

Java8 lambda表达式:

map.forEach((k,v) -> System.out.println("key:"+k+",value:"+v));
    原文作者:xqnode
    原文地址: https://blog.csdn.net/xqnode/article/details/78307345
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞