如何遍历Map的每个元素

方法一:使用entrySet方法:
示例:

public static void main(String[] args) {
        Map param = new HashMap<>(8);
        param.put("1","A");
        param.put("2","B");
        param.put("3","C");
        param.put("4","D");
        param.put("5","E");
        for (Map.Entry p : param.entrySet()) {
            System.out.println("[ key=" + p.getKey() + " , " + p.getValue() + " ]");
        }
    }

结果:
[ key=1 , A ]
[ key=2 , B ]
[ key=3 , C ]
[ key=4 , D ]
[ key=5 , E ]

方法二:使用Java8中map新增的方法forEach
示例:

public static void main(String[] args) {
        Map param = new HashMap<>(8);
        param.put("1","A");
        param.put("2","B");
        param.put("3","C");
        param.put("4","D");
        param.put("5","E");
        param.forEach((key,value) -> System.out.println("[ key=" + key + " , " + value + " ]"));
    }

结果:
[ key=1 , A ]
[ key=2 , B ]
[ key=3 , C ]
[ key=4 , D ]
[ key=5 , E ]
其实map新增的方法forEach底层实现与使用方法一的方法一致,源码解释:

//map接口的默认方法,所有实现map的类都能调用
default void forEach(BiConsumer action) {
		//检查是否为null
        Objects.requireNonNull(action);
        for (Map.Entry entry : entrySet()) {
            K k;
            V v;
            try {
            	//获取key-value
                k = entry.getKey();
                v = entry.getValue();
            } catch(IllegalStateException ise) {
                throw new ConcurrentModificationException(ise);
            }
            //执行
            action.accept(k, v);
        }
    }

你可能感兴趣的:(Java)