Java Stream count方法

描述

使用 JDK 1.8 的新特性 Stream 流 的 count 方法。

题目

定义集合并存储名字,使用 Stream 获取集合元素个数。

题目解决思路

  1. 创建 List 集合,并存储名字。
  2. 使用 stream 方法 获取流对象,使用 count 方法获取集合元素个数。

代码具体实现

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); } }

运行结果如下图:

03 Java Stream count .png

以上案例使用 JDK 1.8 的新特性 Stream 流获取集合元素个数。