[基础篇]-java8之Map遍历5种方式

准备测试数据

private static Map<String, Object> map = new HashMap<>();

static {
    map.put("1001", "value1");
    map.put("1002", "value2");
    map.put("1003", "value3");
    map.put("1004", 1004);
    map.put("1005", 1005);
}

1.通过Map.entrySet遍历key和value

//java8之前
for (Map.Entry<String, Object> entry : map.entrySet()) {
    System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue());
}

//java 8
map.entrySet().forEach(entry -> System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue()));

2.Java8之后遍历方式

//java 8
map.forEach((k, v) -> System.out.println("key:value = " + k + ":" + v));

3.通过forEach迭代键值对

//java8之前
for (String key : map.keySet()) {
    System.out.println("map.get(" + key + ") = " + map.get(key));
}

//java 8
map.keySet().forEach(key -> System.out.println("map.get(" + key + ") = " + map.get(key)));

4.使用迭代器进行遍历

//java8之前
Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Object> entry = iterator.next();
    System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue());
}

//java8
map.entrySet().iterator().forEachRemaining(item -> System.out.println("key:value=" + item.getKey() + ":" + item.getValue()));

5.通过Map.values()遍历所有的value

//java8之前
for (Object value : map.values()) {
    System.out.println("map.value = " + value);
}

//java8
//等价于map.values().forEach(value -> System.out.println(value))
map.values().forEach(System.out::println);

关注程序员小强公众号更多编程趣事,知识心得,热门技术实现与您分享
在这里插入图片描述

你可能感兴趣的:(java基础,java,Map集合)