Java Map中forEach小结
侧边栏壁纸
  • 累计撰写 181 篇文章
  • 累计收到 1,154 条评论

Java Map中forEach小结

萧瑟
2021-05-21 / 0 评论 / 204 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年05月21日,已超过1163天没有更新,若内容或图片失效,请留言反馈。

HashMap

HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。
AbstractMap实现了Map接口,Map接口里面有一个forEach方法。

官方解释

对此映射中的每个条目执行给定操作,直到所有条目已处理或操作引发异常。除非由实现类指定,操作将在入口集迭代的顺序(如果指定了迭代顺序)。
操作引发的异常将中继到调用方。

解读

使用了try catch 抛出的异常为ConcurrentModificationException,标示在线程并发进行读写的时候会出现异常,即,不支持并发操作。

使用方法

Map<Object, Object> map = new HashMap<>();
map.put("name", "xiaose");
map.put("gender", "男");
map.put("phone", "18888888888");
map.put(null, null);
//1.Map的迭代
// 通用的Map迭代方式
System.out.println("==============Map的迭代======================");
for (Map.Entry<Object, Object> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("====================================");
// JDK8的迭代方式
map.forEach((key, value) -> {
    System.out.println(key + ":" + value);
});

输出内容

==============Map的迭代======================
null:null
gender:男
phone:18888888888
name:xiaose
====================================
null:null
gender:男
phone:18888888888
name:xiaose

评论 (0)

取消