在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。


今夜有点儿凉
40 声望3 粉丝

今夜有点儿凉,乌云遮住了月亮。