Stream流
1.引言
说到Stream便容易想到I/O Stream,而实际上,谁规定“流”就一定是“IO流”呢?在Java 8中,得益于Lambda所带来的函数式编程,引入了一个全新的Stream概念,用于解决已有集合类库既有的弊端。
传统集合的多步遍历代码几乎所有的集合(如 Collection
接口或 Map
接口等)都支持直接或间接的遍历操作。而当我们需要对集合中的元素进行操作的时候,除了必需的添加、删除、获取外,最典型的就是集合遍历。例如:
import java.util.ArrayList;
import java.util.List;
public class Demo01ForEach {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("张无忌");
list.add("周芷若");
list.add("赵敏");
list.add("张强");
list.add("张三丰");
for (String name : list) {
System.out.println(name);
}
}
}
这是一段非常简单的集合遍历操作:对集合中的每一个字符串都进行打印输出操作。
循环遍历的弊端
Java 8的Lambda让我们可以更加专注于做什么(What),而不是怎么做(How),这点此前已经结合内部类进行了对比说明。现在,我们仔细体会一下上例代码,可以发现:
- for循环的语法就是“怎么做”
- for循环的循环体才是“做什么”
为什么使用循环?因为要进行遍历。但循环是遍历的唯一方式吗?遍历是指每一个元素逐一进行处理,而并不是从第一个到最后一个顺次处理的循环。前者是目的,后者是方式。
试想一下,如果希望对集合中的元素进行筛选过滤:
- 将集合A根据条件一过滤为子集B;
- 然后再根据条件二过滤为子集C。
那怎么办?在Java 8之前的做法可能为:
import java.util.ArrayList;
import java.util.List;
public class Demo02NormalFilter {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("张无忌");
list.add("周芷若");
list.add("赵敏");
list.add("张强");
list.add("张三丰");
List<String> zhangList = new ArrayList<>();
for (String name : list) {
if (name.startsWith("张")) {
zhangList.add(name);
}
}
List<String> shortList = new ArrayList<>();
for (String name : zhangList) {
if (name.length() == 3) {
shortList.add(name);
}
}
for (String name : shortList) {
System.out.println(name);
}
}
}
这段代码中含有三个循环,每一个作用不同:
- 首先筛选所有姓张的人;
- 然后筛选名字有三个字的人;
- 最后进行对结果进行打印输出。
每当我们需要对集合中的元素进行操作的时候,总是需要进行循环、循环、再循环。这是理所当然的么?不是。循环是做事情的方式,而不是目的。另一方面,使用线性循环就意味着只能遍历一次。如果希望再次遍历,只能再使用另一个循环从头开始。
那,Lambda的衍生物Stream能给我们带来怎样更加优雅的写法呢?
Stream的更优写法
下面来看一下借助Java 8的Stream API,什么才叫优雅:
import java.util.ArrayList;
import java.util.List;
public class Demo03StreamFilter {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("张无忌");
list.add("周芷若");
list.add("赵敏");
list.add("张强");
list.add("张三丰");
list.stream()
.filter(s ‐> s.startsWith("张"))
.filter(s ‐> s.length() == 3)
.forEach(System.out::println);
}
}
直接阅读代码的字面意思即可完美展示无关逻辑方式的语义:获取流、过滤姓张、过滤长度为3、逐一打印。代码中并没有体现使用线性循环或是其他任何算法进行遍历,我们真正要做的事情内容被更好地体现在代码中。
2.流式思想概述
注意:请暂时忘记对传统IO流的固有印象!
整体来看,流式思想类似于工厂车间的“生产流水线”。
当需要对多个元素进行操作(特别是多步操作)的时候,考虑到性能及便利性,我们应该首先拼好一个“模型”步骤 方案,然后再按照方案去执行它。这是一种集合元素的处理方案,而方案就是一种“函数模型”。
这里的 filter 、 map 、 skip
都是在对函数模型进行操作,集合元素并没有真正被处理。只有当终结方法 count执行的时候,整个模型才会按照指定策略执行操作。而这得益于Lambda的延迟执行特性。
备注:“Stream流”其实是一个集合元素的函数模型,它并不是集合,也不是数据结构,其本身并不存储任何元素(或其地址值)。
Stream(流)是一个来自数据源的元素队列
- 元素是特定类型的对象,形成一个队列。 Java中的Stream并不会存储元素,而是按需计算。
- 数据源 流的来源。 可以是集合,数组 等。
和以前的Collection操作不同, Stream操作还有两个基础的特征:
- Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。 这样做可以对操作进行优化, 比如延迟执行(laziness)和短路( short-circuiting)。
- 内部迭代: 以前对集合遍历都是通过Iterator或者增强for的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式,流可以直接调用遍历方法。
当使用一个流的时候,通常包括三个基本步骤:获取一个数据源(source)→ 数据转换→执行操作获取想要的结果,每次转换原有 Stream 对象不改变,返回一个新的 Stream 对象(可以有多次转换),这就允许对其操作可以像链条一样排列,变成一个管道。
3.获取流
java.util.stream.Stream<T>
是Java 8新加入的最常用的流接口(这并不是一个函数式接口)。获取一个流非常简单,有以下几种常用的方式:
-
所有的 Collection 集合都可以通过 stream 默认方法获取流;
-
Stream 接口的静态方法 of 可以获取数组对应的流。
1.根据Collection获取流
首先, java.util.Collection
接口中加入了default方法 stream
用来获取流,所以其所有实现类均可获取流。
import java.util.*;
import java.util.stream.Stream;
public class Demo04GetStream {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// ...
Stream<String> stream1 = list.stream();
Set<String> set = new HashSet<>();
// ...
Stream<String> stream2 = set.stream();
Vector<String> vector = new Vector<>();
// ...
Stream<String> stream3 = vector.stream();
}
}
2.根据Map获取流
java.util.Map
接口不是 Collection
的子接口,且其K-V数据结构不符合流元素的单一特征,所以获取对应的流需要分key、value或entry等情况:
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class Demo05GetStream {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
// ...
Stream<String> keyStream = map.keySet().stream();
Stream<String> valueStream = map.values().stream();
Stream<Map.Entry<String, String>> entryStream = map.entrySet().stream();
}
}
3.根据数组获取流
如果使用的不是集合或映射而是数组,由于数组对象不可能添加默认方法,所以 Stream 接口中提供了静态方法of ,使用很简单:
import java.util.stream.Stream;
public class Demo06GetStream {
public static void main(String[] args) {
String[] array = { "张无忌", "张翠山", "张三丰", "张一元" };
Stream<String> stream = Stream.of(array);
}
}
备注: of 方法的参数其实是一个可变参数,所以支持数组。
4.常用方法
流模型的操作很丰富,这里介绍一些常用的API。这些方法可以被分成两种:
- 延迟方法:返回值类型仍然是 Stream 接口自身类型的方法,因此支持链式调用。(除了终结方法外,其余方法均为延迟方法。)
- 终结方法:返回值类型不再是 Stream 接口自身类型的方法,因此不再支持类似 StringBuilder 那样的链式调用。本小节中,终结方法包括 count 和 forEach 方法。
备注:本小节之外的更多方法,请自行参考API文档。
1.逐一处理:forEach
虽然方法名字叫 forEach ,但是与for循环中的“for-each”昵称不同。
void forEach(Consumer<? super T> action);
该方法接收一个 Consumer 接口函数,会将每一个流元素交给该函数进行处理。
复习Consumer接口
java.util.function.Consumer<T>接口是一个消费型接口。
Consumer接口中包含抽象方法void accept(T t),意为消费一个指定泛型的数据。
基本使用:
import java.util.stream.Stream;
public class Demo12StreamForEach {
public static void main(String[] args) {
Stream<String> stream = Stream.of("张无忌", "张三丰", "周芷若");
stream.forEach(name‐> System.out.println(name));
}
}
2.过滤:filter
可以通过 filter 方法将一个流转换成另一个子集流。方法签名:
Stream<T> filter(Predicate<? super T> predicate);
该接口接收一个 Predicate 函数式接口参数(可以是一个Lambda或方法引用)作为筛选条件。
复习Predicate接口
此前我们已经学习过 java.util.stream.Predicate
函数式接口,其中唯一的抽象方法为:
boolean test(T t);
该方法将会产生一个boolean值结果,代表指定的条件是否满足。如果结果为true,那么Stream流的 filter 方法将会留用元素;如果结果为false,那么 filter 方法将会舍弃元素。
基本使用
Stream流中的 filter 方法基本使用的代码如:
import java.util.stream.Stream;
public class Demo07StreamFilter {
public static void main(String[] args) {
Stream<String> original = Stream.of("张无忌", "张三丰", "周芷若");
Stream<String> result = original.filter(s ‐> s.startsWith("张"));
}
}
在这里通过Lambda表达式来指定了筛选的条件:必须姓张。
3.映射:map
如果需要将流中的元素映射到另一个流中,可以使用 map 方法。方法签名:
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
该接口需要一个 Function 函数式接口参数,可以将当前流中的T类型数据转换为另一种R类型的流。
复习Function接口
此前我们已经学习过 java.util.stream.Function
函数式接口,其中唯一的抽象方法为:
R apply(T t);
这可以将一种T类型转换成为R类型,而这种转换的动作,就称为“映射”。
基本使用
Stream流中的 map 方法基本使用的代码如:
import java.util.stream.Stream;
public class Demo08StreamMap {
public static void main(String[] args) {
Stream<String> original = Stream.of("10", "12", "18");
Stream<Integer> result = original.map(str‐>Integer.parseInt(str));
}
}
这段代码中, map 方法的参数通过方法引用,将字符串类型转换成为了int类型(并自动装箱为 Integer 类对象)。
4.多映射:flatmap
如果需要将流中的子元素映射到另一个流中,可以使用 flatmap 方法。方法签名:
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
基本使用
Stream流中的 flatmap 方法基本使用的代码如:
准备数据代码
private static List<Student> computerClub = Arrays.asList(
new Student("2015134001", "小明", 15, "1501"),
new Student("2015134003", "小王", 14, "1503"),
new Student("2015134006", "小张", 15, "1501"),
new Student("2015134008", "小梁", 17, "1505")
);
private static List<Student> basketballClub = Arrays.asList(
new Student("2015134012", "小c", 13, "1503"),
new Student("2015134013", "小s", 14, "1503"),
new Student("2015134015", "小d", 15, "1504"),
new Student("2015134018", "小y", 16, "1505")
);
private static List<Student> pingpongClub = Arrays.asList(
new Student("2015134022", "小u", 16, "1502"),
new Student("2015134021", "小i", 14, "1502"),
new Student("2015134026", "小m", 17, "1504"),
new Student("2015134027", "小n", 16, "1504")
);
private static List<List<Student>> allClubStu = new ArrayList<>();
和map方法的对比
allClubStu.add(computerClub);
allClubStu.add(basketballClub);
allClubStu.add(pingpongClub);
//map 一对一 映射处理
List<Stream<Student>> list = allClubStu.stream().map(s ->
s.stream().filter(c -> c.getAge() > 15)
).collect(Collectors.toList());
/* List<Stream<StudentDTO>> streams = allClubStu.stream().map(s -> {
Stream<StudentDTO> studentDTOStream = s.stream().filter(student -> student.getAge() > 15)
.map(student -> {
StudentDTO studentDTO = StudentDTO.builder().age(student.getAge())
.classNum(student.getClassNum())
.name(student.getName())
.studentNum(student.getStudentNum()).build();
return studentDTO;
});
return studentDTOStream;
}).collect(Collectors.toList());*/
//flatMap 一对多映射处理,深入到多个stream内部去处理子元素,统一输出
List<Student> studentList = allClubStu.stream().flatMap(e -> e.stream().
filter(student -> student.getAge() > 15)).collect(Collectors.toList());
studentList.forEach(System.out::println);
}
5.统计个数:count
正如旧集合 Collection 当中的 size 方法一样,流提供 count 方法来数一数其中的元素个数:
long count();
该方法返回一个long值代表元素个数(不再像旧集合那样是int值)。基本使用:
import java.util.stream.Stream;
public class Demo09StreamCount {
public static void main(String[] args) {
Stream<String> original = Stream.of("张无忌", "张三丰", "周芷若");
Stream<String> result = original.filter(s ‐> s.startsWith("张"));
System.out.println(result.count()); // 2
}
}
6.取用前几个:limit
limit 方法可以对流进行截取,只取用前n个。方法签名:
Stream<T> limit(long maxSize);
参数是一个long型,如果集合当前长度大于参数则进行截取;否则不进行操作。基本使用:
import java.util.stream.Stream;
public class Demo10StreamLimit {
public static void main(String[] args) {
Stream<String> original = Stream.of("张无忌", "张三丰", "周芷若");
Stream<String> result = original.limit(2);
System.out.println(result.count()); // 2
}
}
7.跳过前几个:skip
如果希望跳过前几个元素,可以使用 skip 方法获取一个截取之后的新流:
Stream<T> skip(long n);
如果流的当前长度大于n,则跳过前n个;否则将会得到一个长度为0的空流。基本使用:
import java.util.stream.Stream;
public class Demo11StreamSkip {
public static void main(String[] args) {
Stream<String> original = Stream.of("张无忌", "张三丰", "周芷若");
Stream<String> result = original.skip(2);
System.out.println(result.count()); // 1
}
}
8.执行:peek
在流的每个元素恢复运行之前的时候插入一个执行操作:
Stream<T> peek(Consumer<? super T> action);
该方法的基本使用代码如:
public class PeekTestThree {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(4, 7, 9, 11, 12);
list.stream()
.peek(x -> System.out.println("stream: " + x))
.map(x -> x + 2)
.peek(x -> System.out.println("map: " + x))
.filter(x -> x % 2 != 0)
.peek(x -> System.out.println("filter: " + x))
.limit(2)
.peek(x -> System.out.println("limit: " + x))
.collect(toList());
}
}
输出结果如下:
stream: 4
map: 6
stream: 7
map: 9
filter: 9
limit: 9
stream: 9
map: 11
filter: 11
limit: 11
准备数据代码:
实体类:员工类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee implements Serializable {
private static final long serialVersionUID = 4775629632953317597L;
/**
* ID
*/
public int id;
/**
* 姓名
*/
public String name;
/**
* 年龄
*/
public int age;
/**
* 工资
*/
public int salary;
/**
* 入职年数
*/
public int year;
}
添加集合代码
List<Employee> employeeList = new ArrayList<Employee>(){
{
add(new Employee(1,"张三",25,7000,3));
add(new Employee(2,"李四",24,6000,2));
add(new Employee(3,"王五",28,9000,4));
add(new Employee(4,"赵六",29,9000,4));
add(new Employee(5,"田七",24,6500,2));
}
};
9.排序:sorted
//不传参数默认是正序排列
Stream<Employee> sorted = stream.sorted();
//参数为Comparator函数式接口,意思是根据员工工资的高低排序
Stream<Employee> sortedStream = stream.sorted((e1, e2) -> e1.salary - e2.salary);
10.聚合:max,min
//参数为Comparator函数式接口,获取员工中年龄的最大值最小值
//返回值是optional对象
Optional<Employee> max = stream.max((e1, e2) -> e1.age - e2.age);
Optional<Employee> min = stream.min((e1, e2) -> e1.age - e2.age);
11.获取:findAny,findFrist
//获取容器中任意一个元素/第一个元素
//返回值为optional对象
Optional<Employee> any = stream.findAny();
Optional<Employee> first = stream.findFirst();
12.判断:anyMatch,allMatch,noneMatch
//参数为Predicate函数式接口,这里用的lambda表达式
//anyMatch()方法作用判断,只要有一个元素满足条件就返回true
boolean anyMatch = stream.anyMatch(v -> v.salary > 8000);
//allMatch()方法作用判断,所有元素满足条件就返回true
boolean allMatch = stream.allMatch(v -> v.salary > 8000);
//noneMatch()方法作用判断,没有一个元素满足条件就返回true
boolean noneMatch = stream.noneMatch(v -> v.salary > 8000);
13.收集:collect
//收集,把流数据收集成新的类型容器
//参数为Suppoet函数式接口
List<Employee> list = stream.collect(Collectors.toList());
Set<Employee> collect = stream.collect(Collectors.toSet());
//这里toMap里面传的参数为Function函数式接口,员工姓名作为key,工资作为值
Map<String, Integer> map = stream.collect(Collectors.toMap(Employee::getName, Employee::getSalary));
14.归约:reduce
BinaryOperator是函数式接口,继承了BiFunction<T,T,T>,内部有一个apply抽象方法,接收两个参数,返回一个结果,R apply(T t, U u)
package java.util.function;
import java.util.Objects;
/**
* Represents a function that accepts two arguments and produces a result.
* This is the two-arity specialization of {@link Function}.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object, Object)}.
*
* @param <T> the type of the first argument to the function
* @param <U> the type of the second argument to the function
* @param <R> the type of the result of the function
*
* @see Function
* @since 1.8
*/
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*/
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}
方式一: Optional reduce(BinaryOperator accumulator)
//对Stream中的数据通过累加器accumulator迭代计算,最终得到一个Optional对象
Optional<Integer> reduce = Stream.of(1, 2, 3, 4).reduce((a, b) -> {
System.out.println("每次操作前初始值:" + a);
a += b;
System.out.println("每次操作加的值:" + b);
System.out.println("操作之后的结果:" + a);
//把结果值返回作为下一次操作的初始值
return a;
});
System.out.println("最终结果为:"+reduce.get());
方式二: T reduce(T identity, BinaryOperator accumulator)
//提供一个跟Stream中数据同类型的初始值identity,通过累加器accumulator迭代计算Stream中的数据,得到一个跟Stream中数据相同类型的最终结果
Integer reduce2 = Stream.of(1, 2, 3, 4).reduce(10, (a, b) -> {
//这里的第一次打印的值,一定是你传的identity的值
System.out.println("每次操作前初始值:" + a);
a += b;
System.out.println("每次操作加的值:" + b);
System.out.println("操作之后的结果:" + a);
//把结果值返回作为下一次操作的初始值
return a;
});
System.out.println("最终结果为:"+reduce2);
方式三: U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator combiner)
Integer reduce3 = Stream.of(1, 2, 3, 4).parallel().reduce(10, (a, v) -> {
//用并行操作每次初始值都是指定的值
System.out.println("每次操作前初始值:" + a + "/" + v);
a += v;
System.out.println("每次操作加的值:" + v);
System.out.println("操作之后的结果:" + a);
//比如这里执行4次,出现返回的值为: 11 12 13 14
return a;
}, (a, v) -> {
//这里只会是并行流才会执行
//这里的a,v指定是return回去的2个值,就是上面的值,第一轮是 11 12 第二轮是 13 14 ,因为上面返回的值完了,所以轮到当前返回的值了,第三轮是 23 27
System.out.println("并行每次操作前初始值:" + a + "/" + v);
a += v;
System.out.println("并行每次操作加的值:" + v);
System.out.println("并行操作之后的结果:" + a);
//最终的结果由自己返回
return a;
});
//最终的值为50
System.out.println("最终的值为:"+reduce3);
15.组合:concat
如果有两个流,希望合并成为一个流,那么可以使用 Stream 接口的静态方法 concat :
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)
备注:这是一个静态方法,与 java.lang.String 当中的 concat 方法是不同的。
该方法的基本使用代码如:
import java.util.stream.Stream;
public class Demo12StreamConcat {
public static void main(String[] args) {
Stream<String> streamA = Stream.of("张无忌");
Stream<String> streamB = Stream.of("张翠山");
Stream<String> result = Stream.concat(streamA, streamB);
}
}
想了解函数式接口可以查看我另一篇文章:
函数式接口