Java8 - Map更优雅的迭代方式:forEach

版权声明:知识诚无价,分享价更高。 https://blog.csdn.net/u013955940/article/details/83053977

BiConsumer

用于两个参数之间进行操作的函数式接口是 BiConsumer。这个函数式接口正好用来操作 Mapkeyvalue。JDK8强化了针对 Map 类的迭代方式,新增了一个默认方法 forEach,它接收一个 BiConsumer 函数。JDK给出的描述如下:

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.(对该映射中的每个条目执行给定的操作,直到所有条目已被处理或动作抛出异常为止。)

下面是代码例子:

// 创建一个Map
Map<String, Object> infoMap = new HashMap<>();
infoMap.put("name", "Zebe");
infoMap.put("site", "www.zebe.me");
infoMap.put("email", "[email protected]");
// 传统的Map迭代方式
for (Map.Entry<String, Object> entry : infoMap.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue());
}
// JDK8的迭代方式
infoMap.forEach((key, value) -> {
    System.out.println(key + ":" + value);
});

本文首发于个人独立博客,文章链接:http://www.zebe.me/java-8-map-for-each

猜你喜欢

转载自blog.csdn.net/u013955940/article/details/83053977