关于java: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。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理