Java 8使用Stream来遍历Map的几种方式
文章目录
在Java 8中,可以使用Stream来遍历Map。以下是一些示例代码:
1.遍历Map的键:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.keySet().forEach(key -> System.out.println(key));2.遍历Map的值:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.values().forEach(value -> System.out.println(value));3.遍历Map的键值对:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.forEach((key, value) -> System.out.println(key + " : " + value));4.使用Stream的方式遍历Map的键值对:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.entrySet().stream().forEach(entry ->
System.out.println(entry.getKey() + " : " + entry.getValue()));以上是几种常见的遍历Map的方法,在Java 8中,使用Stream可以更加简洁和方便地遍历Map。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论