使用 JDK 1.8 的新特性 Stream 流 的 count 方法。
定义集合并存储名字,使用 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,"刘备","张飞","张翼德","关羽","张良");
// 获取集合元素个数
long count = list.stream().count();
System.out.println("【集合大小】:" + count);
}
}
运行结果如下图:
以上案例使用 JDK 1.8 的新特性 Stream 流获取集合元素个数。