Java 8 中的 Map 遍历方法 - 使用 Stream 和 forEach
在 Java 8 中,可以使用 Stream 来遍历 Map。以下是一个示例:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put('A', 1);
map.put('B', 2);
map.put('C', 3);
// 使用 forEach 遍历 Map
map.forEach((key, value) -> System.out.println(key + ': ' + value));
// 使用 Stream 的 forEach 遍历 Map
map.entrySet().stream()
.forEach(entry -> System.out.println(entry.getKey() + ': ' + entry.getValue()));
// 使用 Stream 的 forEach 遍历 Map 的键
map.keySet().stream()
.forEach(key -> System.out.println(key));
// 使用 Stream 的 forEach 遍历 Map 的值
map.values().stream()
.forEach(value -> System.out.println(value));
}
}
输出结果:
A: 1
B: 2
C: 3
A: 1
B: 2
C: 3
A
B
C
1
2
3
这里使用了 forEach 方法、Stream 以及 entrySet()、keySet()、values() 等方法来遍历 Map 的键值对、键和值。您可以根据自己的需求选择适合的方式来遍历 Map。
原文地址: https://www.cveoy.top/t/topic/kgvR 著作权归作者所有。请勿转载和采集!