Java 8新特性 - (2)Stream API

分享到:

文章目录


什么是Stream API

Stream API让开发者能够以一种声明的方式处理数据源(集合、数组等),它专注于对数据源进行各种高效的聚合操作(aggregate operation)和大批量数据操作 (bulk data operation)。

Stream API将处理的数据源看做一种Stream(流),Stream(流)在Pipeline(管道)中传输和运算,支持的运算包含筛选、排序、聚合等,当到达终点后便得到最终的处理结果。如果说集合讲的的数据,那么流讲的就是计算!

几个关键概念:

  1. 元素: Stream是一个来自数据源的元素队列,Stream本身并不存储元素。
  2. 数据源: 即Stream的来源, 包含集合、数组、I/O channel、generator(发生器)等。
  3. 聚合操作: 类似SQL中的filter、map、find、match、sorted等操作
  4. 管道运算: Stream在Pipeline中运算后返回Stream对象本身,这样多个操作串联成一个Pipeline,并形成fluent风格的代码。这种方式可以优化操作,如延迟执行(laziness)和短路( short-circuiting)。
  5. 内部迭代: 不同于java 8以前对集合的遍历方式(外部迭代),Stream API采用访问者模式(Visitor)实现了内部迭代。
  6. 并行运算: Stream API支持串行(stream())或并行(parallelStream())的两种操作方式。

特点:

  • Stream API的使用和同样是java8新特性的lambda表达式密不可分,可以大大提高编码效率和代码可读性。
  • Stream API提供串行和并行两种操作,其中并行操作能发挥多核处理器的优势,使用fork/join的方式进行并行操作以提高运行速度。
  • Stream API进行并行操作无需编写多线程代码即可写出高效的并发程序,且通常可避免多线程代码出错的问题。

注意:

  • Stream 自己不会存储元素。
  • Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
  • Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream操作的三个步骤

  1. 创建Stream:一个数据源(如: 集合、数组), 获取一个流。
  2. 中间操作:一个中间操作链,对数据源的数据进行处理。
  3. 终止操作(终端操作):一个终止操作,执行中间操作链,并产生结果。

创建Stream

(1) 获取Stream

Java 8中Collection接口被扩展,提供两种获取流的方法:

  • stream() 返回一个顺序流
  • parallelStream()返回一个并行流
1default Stream stream() // 返回一个顺序流
2
3default Stream parallelStream() // 返回一个并行流
1List<String> list = new ArrayList<>();
2
3// 顺序流
4Stream<String> stream1 = list.stream();
5
6// 并行流
7Stream<String> parallelStream = list.parallelStream();

(2) 由数组创建流

Arrays中静态方法stream()获取数组流

Java 8 中的 Arrays 的静态方法 stream() 可以获取数组流:

1static Stream stream(T[] array) // 返回一个流重载形式,能够处理对应基本类型的数组
2
3public static IntStream stream(int[] array)
4
5public static LongStream stream(long[] array)
6
7public static DoubleStream stream(double[] array)
1Employess[] emps = new Employess[10];
2Stream<Employess> stream2 = Arrays.stream(emps);

(3)由值创建流

可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。

1public static Stream of(T... values)  // 返回一个流
1Stream<String> stream3 = Stream.of("aa", "bb", "cc");

(4)由函数创建流

由函数创建流可以创建无限流。可以使用静态方法 Stream.iterate() 和Stream.generate(), 创建无限流 。

1// 迭代
2public static Stream iterate(final T seed, final UnaryOperator f)
3
4// 生成
5public static Stream generate(Supplier s)
1// 迭代
2Stream<Integer> stream4 = Stream.iterate(0, (x) -> x + 2).limit(10);
3
4// 生成
5Stream.generate(() -> Math.random()).limit(5);

中间操作

(1) 筛选与切片

方法 描述
filter(Predicate p) 接收Lambda,从流中排除某些元素
distinct() 筛选,通过流所生成元素的hashCode()和equals()去除重复元素
limit(long maxSize) 截断流,使其元素不超过给定数量
skip(long n) 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n)互补

(2) 映射

方法 描述
map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并映射成一个新元素
mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,并产生一个新的DoubleStream
mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,并产生一个新的IntStream
mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,并产生一个新的LongStream
Flat(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

(3) 排序

方法 描述
sorted() 产生一个新流,其中按自然顺序排列
sorted(Comparator comp) 产生一个新流,其中按比较器顺序排列

终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List, Integer,甚至是void

(1) 查找与匹配

方法 描述
allMatch(Predicate p) 检查是否匹配所有元素
anyMatch(Predicate p) 检查是否至少匹配一个元素
noneMatch(Predicate p) 检查是否所有元素都不匹配
findFirst() 返回第一个元素
findAny() 返回当前流中的任意一个元素
count() 返回流中元素总数
max(Comparator c) 返回流中最大值
min(Comparator c) 返回流中最小值
forEach(Comparator c) 内部迭代。与之相反的是,使用Collection接口需要用户去做迭代,称为外部迭代

(2) 规约

方法 描述
reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回T
reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。返回Optional

(3) 收集

方法 描述
collect(Collector c) 将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法

Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、 Set、 Map)。但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例, 具体方法与实例如下表

方法 返回类型 作用
toList List 把流中元素收集到List
toSet Set 把流中元素收集到Set
toCollection Collection 把流中元素收集到创建的集合
counting Long 计算流中元素的个数
summingInt Integer 对流中元素的整数属性求和
averageingInt Double 计算流中元素Integer属性的平均值
summarizingInt IntSummaryStatistics 收集流中Integer属性的统计值。如平均值
joining String 连接流中每个字符串
maxBy Optional 根据比较器选择最大值
minBy Optional 根据比较器选择最小值
reducing 规约产生的类型 从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值
collectingAndThen 转换函数返回的类型 包裹另一个收集器,对其结果转换函数
groupingBy Map<K, List> 根据某属性值对流分组,属性为K,结果为V
partitioningBy Map<Boolean, List> 根据true或者false进行分区

示例:

 1List<Employee> emps = list.stream().collect(Collectors.toList());
 2
 3Set<Employee> emps = list.stream().collect(Collectors.toSet());
 4
 5Collection<Employee> emps = list.stream().collect(Collectors.toCollection(ArrayList::new));
 6
 7long count = list.stream().collect(Collectors.counting());
 8
 9inttotal = list.stream().collect(Collectors.summingInt(Employee::getSalary));
10
11doubleavg = list.stream().collect(Collectors.averagingInt(Employee::getSalary));
12
13IntSummaryStatisticsiss = list.stream().collect(Collectors.summarizingInt(Employee::getSalary));
14
15String str = list.stream().map(Employee::getName).collect(Collectors.joining());
16
17Optional<Emp> max = list.stream().collect(Collectors.maxBy(comparingInt(Employee:getSalary)));
18
19Optional<Emp> min = list.stream().collect(Collectors.minBy(comparingInt(Employee:getSalary)));
20
21inttotal = list.stream().collect(Collectors.reducing(0, Employee::getSalary, Integer::sum));
22
23inthow = list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List:size));
24
25Map<Emp.Status, List<Emp>> map = list.stream().collect(Collectors.groupingBy(Employee::getStatus));
26
27Map<Boolean, List<Emp>> vd = list.stream.collect(Collectors.partitioningBy(Employee::getManage));

参考: