使用 JDK 1.8 的新特性 Stream 流 的 forEach 方法。
使用 Stream 流遍历集合并打印集合元素。
public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
// 创建集合
List<String> list = new ArrayList<>();
// 存储元素
Collections.addAll(list,"刘备","张飞","赵云","诸葛亮");
// 使用流打印集合元素
list.stream().forEach(s -> System.out.println(s));
}
}
运行结果如下图:
以上案例使用 JDK 1.8 的新特性 Stream 流遍历集合。