java stream介绍

介绍

Java 8 中的 Stream不是 io流,是 Java 8 新增的功能,用于 处理数据

类比

其功能相当于 SQL 查询数据:

select name,age,sex
from student
where age<20   -- 过滤
limit 10,20    -- 截取数据
order by age   -- 排序

其功能相当于 SQL 统计数据:

select count(id),max(age),min(age)  -- 统计
from student
where age<20   -- 过滤
limit 10,20    -- 截取数据
order by age   -- 排序

使用

步骤

  1. 创建 Stream,一般通过集合(ListSet、数组)创建

  2. 中间操作,如:过滤、截取数据,调用该方法后会返回 Stream ,通过该 Stream 还可以调用其他方法

  3. 终结操作,如:统计、打印,调用该方法后,不会返回 Stream,无法再次调用其他方法

特点

  • stream不能存储数据
  • stream用于计算,如:过滤、统计
  • stream不会改变源数据,即:上图集合中的数据不会改变
  • stream中的方法,一般只能调用一次,再次调用报错

lambda表达式

Stream 搭配 lambda表达式,能够写出非常简洁的代码,提高开发速度

缺点:不易阅读

优点

Java 集合 处理时,极大提高开发速度,代码简洁干净


原文出处:https://malaoshi.top/show_1IX5H8Mf2b95.html