Stream流

作用

  • 结合了Lambda表达式, 简化集合和数组的操作

使用步骤

  • 先得到一条Stream流(流水线), 并把数据放上去

    获取方式 方法名 说明
    单列集合 default Stream stream() Collection中的默认方法
    双列集合 无法直接使用Stream流
    数组 public static Stream stream(T[] array) Arrays工具类中的静态方法
    一堆零散数据 public static Stream of(T… values) Stream接口中的静态方法
  • 使用中间方法对流水线上的数据进行操作

    名称 说明
    Stream filter(Predicate<? super T> predicate) 过滤
    Stream limit(long maxSize) 获取前几个元素
    Stream skip(long n) 跳过前几个元素
    Stream distinct() 元素去重, 依赖(hashCode和equals方法)
    static Stream concat(Stream a, Stream b) 合并a和b两个流为一个流
    Stream map(Function<T, R> mapper) 转换流中的数据类型
    • 注意1: 中间方法, 返回新的Stream流, 原来的Stream流只能使用一次, 建议使用链式编程

    • 注意2: 修改Stream流中的数据, 不会影响原来集合或者数组中的数据

  • 使用终结方法对流水线上的数据进行操作

    名称 说明
    void forEach(Consumer action) 遍历
    long count() 统计
    toArray() 收集流中的数据, 放到数组中
    collect(Collector collector) 收集流中的数据, 放到集合中