在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。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。