---
title: " Java 8 Stream API 实用指南"
author: "fooler5"
date: "2017-12-08T18:09:56Z"
tags: []
categories: ["编程语言"]
slug: "java-8-stream-api"
draft: false
lastmod: "2017-12-08T18:09:56Z"
id: 2404195
url: "https://fooler5.iteye.com/blog/2404195"
---

引用

来源：[gitbook](http://gitbook.cn/books/59ff3c278c83803b208e51e6/index.html?utm_source=iteyes)  
作者：[阿福](http://gitbook.cn/gitchat/author/59eceece6ee8e94cfe13aeeb?utm_source=iteyes)

本文作为 Stream API 的 “使用指南”，主要侧重于 “实用”，并不会关注太多的实现细节，当然，不是简单地罗列接口，而是尽可能地向读者展示 Stream API 的全貌。

**开始之前**

作为 Java API 的新成员，Stream API “允许以声明式的方式处理数据集合”。回顾 “内容介绍” 部分，我们阅读了以下的代码：

代码

01. class Good {
02. String name;               // 商品名称
03. long price;               // 价格
04. long sales;               // 销量
05. List&lt;String&gt; categories;  // 类别
06. // ... 省略 constructor、getter / setter
07. // ... 省略 toString
08. }
09. void process(List&lt;Good&gt; goods) {
10. //
11. // 筛选 price &gt; 500 & sales &lt; 200 的商品, 价格最高的 10 件商品, 价格减半（双十一来啦！）
12. //
13. goods.stream()
14. .filter(c -&gt; c.getPrice() &gt; 500 && c.getSales() &lt; 200)
15. .sorted(Comparator.comparing(Good::getPrice).reversed())
16. .limit(10)
17. .forEach(c -&gt; { c.setPrice(c.getPrice() / 2); });
18. }

即使没有 Stream API，我们依然能够通过完成需求，但无法做到如此简洁、清晰。（本文最后的部分，还会进一步探讨 Stream API 在并发方面的优势。）

开始使用 Stream API 之前，我们需要了解，Stream 是什么？有哪些比较重要的概念？为此，我们针对上文的代码绘制了示意图：

![](http://dl2.iteye.com/upload/attachment/0127/9524/1f361980-f122-3629-a374-7a849e82c5af.png "点击查看原始大小图片")

图中所示，整个过程就是将 goods 元素集合作为一个 “序列”，进行一组 “流水线” 操作，其中：

- goods 集合提供了元素序列的数据源，通过 stream() 方法获得 Stream
- filter / sorted / limit 进行数据处理，“连接起来” 构成 “流水线”
- forEach 最终执行

需要说明，filter / sorted / limit 的返回值均为 Stream（类似于 Builder 模式），但它们并不立即执行，而是构成了 “流水线”，直到 forEach：最终执行，并且关闭 Stream。因此：

- 将 filter / sorted / limited 等能够 “连接起来”，并且返回 Stream 的方法称为 “中间操作”（Intermediate）
- 将 forEach 等最终执行，并且关闭 Stream 的方法称为 “终止操作” （Terminal）

特别地，需要记住：Stream 的中间操作并不是立即执行，而是 “延迟的”、“按需计算”；并且，完成 “终止操作” 后，Stream 将被关闭。

现在，我们应当了解 Stream 的关键概念：数据源、中间操作构成 “流水线”、终止操作，对于 Stream 的定义，我们直接引用 Java doc：

引用

A sequence of elements supporting sequential and parallel aggregate operations.

代码

1. package java.util.stream;
2. public interface Stream&lt;T&gt; extends BaseStream&lt;T, Stream&lt;T&gt;&gt; {
3. // ...
4. }

代码所示：Stream 中序列元素的类型，通过泛型表达。对于原始类似，除了包装类外，Stream API 同时提供了原始类型的 Stream：IntStream、LongStream 以及 DoubleStream

本质而言，Stream API 的 “流水线” 操作，最终仍然依赖于迭代，但与使用 Collection API 直接构建迭代的代码不同，Stream API 通过参数的形式接收我们提供的操作，由其内部实现迭代。

而所谓 “我们提供的操作”，请参考 “Lambda 表达式 & 方法引用”。

**Lambda 表达式 & 方法引用**

Lambda 表达式，或者 λ，虽然并不是新鲜事物，但其越来越受到重视，尤其是 Java 8（以及 C++11）将 Lambda 表达式纳入标准以后。暂且不谈论 “函数式编程” 的话题，我们先了解 Lambda 表达式如何使用。

**Lamba 表达式**

对于 Java 开发者，匿名类是很常见的东西，例如：

代码

01. @FunctionalInterface
02. interface PriceCalculator {
03. long calculate(Good good);
04. };
05. public void process(List&lt;Good&gt; goods, PriceCalculator calculator) {
06. // 计算商品价格
07. }
08. //
09. // 实现 PriceCalculator 接口的匿名类实例，作为 process 参数
10. //
11. process(goods, new PriceCalculator() {
12. @Override
13. public long calculate(Good good) {
14. return good.getPrice();
15. }
16. });

接口 PriceCalculator 只有一个方法，我们将只有一个抽象方法的接口，称为 “函数式接口”，并以 @FunctionalInterface 进行标记。（注意，Java 8 允许接口提供方法实现，即 “默认方法”，函数式接口必须包含且仅包含一个抽象方法，对于提供实现的默认方法，没有限制）

Lambda 表达式，其本质即为函数式接口的一个实例：

代码

01. //
02. // 示例 #1: args -&gt; { statement; }
03. //
04. process(goods, (good) -&gt; {
05. return good.getPrice();
06. });
07. //
08. // 示例 #2：args -&gt; expression
09. //
10. process(goods, (good) -&gt; good.getPrice());

函数式接口中抽象方法的签名即为 Lambda 表达式的签名，称为 “函数描述符”。Lambda 表达式的类型，由 Java 编译器根据上下文推断获得。

**方法引用**

方法引用，即为特定情况下 Lambda 表达式的简化，例如：

代码

1. process(goods, Good::getPrice);

对于 Lambda 表达式到方法引用的简化，我们提供以下规则：

Lambda 表达式 方法引用 (args) -&gt; ClassName.staticMethod(args) ClassName::staticMethod (arg0, ...) -&gt; arg0.instanceMethod(...) ClassName::instanceMethod (args) -&gt; expression.instanceMethod(args) expression::instanceMethod

特别的，对于构造函数的方法引用：ClassName::new

**开始使用 Stream API**

本章节将阐述 Stream 的生成、操作、数据收集，主要介绍 Stream API 的常用接口与辅助方法。为了便于我们试验示例的代码，我们先说明 forEach(Consumer&lt;? super T&gt;)。

正如前面章节所说，forEach(Consumer&lt;? super T&gt;) 是一个 “终止操作”，它遍历 Stream 的元素序列，通过函数式接口 Consumer&lt;? super T&gt; 的 accept(T) 执行特定操作。Consumer&lt;? super T&gt; 的声明：

代码

1. @FunctionalInterface
2. public interface Consumer&lt;T&gt; {
3. void accept(T);
4. }

以下的阐述中，将通过 forEach(System.out::println) 将 Stream 的元素序列输出。

**生成 Stream**

**由集合 & 数组生成 Stream**

Stream 作为元素的 “序列”，自然而然地，我们想到通过集合、数组生成 Stream。

Java 8 的 Collection 接口添加了 Stream&lt;E&gt; stream() 方法，由集合生成 Stream，例如：

代码

1. //
2. // 输出商品集合
3. //
4. void print(List&lt;Good&gt; goods) {
5. goods.stream().forEach(System.out::println);
6. }

java.util.Arrays 提供了 stream(T\[]) 的静态方法，由 T\[] 数组生成 Stream：

代码

1. //
2. // 输出商品数组
3. //
4. void print(Good\[] goods) {
5. Arrays.stream(goods).forEach(System.out::println);
6. }

特别地，当数组元素类型 T 是原始类型，静态方法 stream(T\[]) 将返回原始类型的 Stream。

通过集合或数组获得的 Stream，是 “有限” 的。

**直接创建 Stream**

除了由集合和数组生成 Stream，Stream API 提供了静态方法 Stream.generate(Supplier&lt;T&gt;)、Stream.iterator(final T, final UnaryOperator&lt;T&gt;)，直接创建 Stream。

Stream.generate(Supplier&lt;T&gt;) 通过参数 Supplier&lt;T&gt; 获取 Stream 序列的新元素

代码

1. //
2. // 生成指定数量的商品并输出
3. //
4. void generate(int number) {
5. Stream.generate(Good::new).limit(number).forEach(System.out::println);
6. }

Stream.iterator(final T, final UnaryOperator&lt;T&gt;) 提供了一种 “迭代” 的形式：第一个元素，以及第 n 个元素到第 n + 1 个元素的生成方式 UnaryOperator&lt;T&gt;。

代码

1. //
2. // 生成指定数量的序列 1, 2, 4, 8, 16 ... 并输出
3. //
4. void generateSequence(int number) {
5. Stream.iterate(0, n -&gt; n * 2).limit(number).forEach(System.out::println);
6. }

通过 Stream.generate(Supplier&lt;T&gt;)、Stream.iterator(final T, final UnaryOperator&lt;T&gt;)，将产生 “无限的” Stream，以上的示例中，使用 limit 进行了 Stream 截断。

**操作 Stream**

filter

filter 是 “中间操作”，以 Predicate&lt;? super T&gt; 的实例作为参数，进行 Stream 过滤，仅保留符合条件的元素。Predicate&lt;? super T&gt; 作为常用的函数式接口，其声明如下：

代码

1. @FunctionalInterface
2. public interface Predicate&lt;T&gt; {
3. boolean test(T);
4. }

例如：

代码

1. //
2. // 过滤高于指定价格的商品
3. //
4. void filterByPrice(List&lt;Good&gt; goods, long price) {
5. goods.stream().filter(c -&gt; c.getPrice() &gt; price).forEach(System.out::println);
6. }

**anyMatch / allMatch / noneMatch**

anyMatch、allMatch、noneMatch，都是 “终止操作”，与 filter 接收相同的参数，其功能顾名思义，例如：

代码

1. //
2. // 检查商品集合是否包含指定名称的商品
3. //
4. boolean hasGoodWithName(List&lt;Good&gt; goods, String name) {
5. return goods.stream().anyMatch(c -&gt; name.equals(c.getName()));
6. }

**findAny / findFirst**

findAny、findFirst，都是 “终止操作”，分别获取 Stream 元素序列的任意元素和第一个元素：

代码

1. //
2. // 获取商品集合中任意名称为指定名称的商品
3. //
4. Optional&lt;Good&gt; findAnyGoodWithName(List&lt;Good&gt; goods, String name) {
5. return goods.stream().filter(c -&gt; name.equals(c.getName())).findAny();
6. }

findAny、findFirst 的返回值都是 Optional&lt;T&gt; 类型，避免了 Stream 序列为空时返回 null。关于 Optional&lt;T&gt; 类型，不属于本文的范围，请参阅 Java doc。

相比较于 findFisrt，findAny 更适合于并发的场景。

**map**

map 是中间操作，将 Stream 序列的元素映射为其他的元素，以 Function&lt;? super T, ? extends R&gt; 作为参数，其声明如下：

代码

1. @FunctionalInterface
2. public interface Function&lt;T, R&gt; {
3. R apply(T);
4. }

代码所示，Function&lt;? super T, ? extends R&gt; 提供了 Stream 序列的元素映射为其他元素的途径，例如：

代码

1. //
2. // 输出商品的名称
3. //
4. void printName(List&lt;Good&gt; goods) {
5. goods.stream().map(Good::getName).forEach(System.out::println);
6. }

此外，Stream 提供 mapToInt、mapToLong、mapToDouble，将 Stream 映射为原始类型 Stream。

**flatMap**

map 直接将 Stream 序列的元素映射到新的元素，假如 map 映射获得的是 Stream，flatMap 能够将各个 Stream 的元素合并到一个 Stream 中，例如：

代码

1. //
2. // 获取商品集合的分类
3. //
4. void getCategories(List&lt;Good&gt; goods) {
5. goods.stream().flatMap(c -&gt; c.getCategories().stream()).forEach(System.out::println);
6. }

**distinct**

distinct 是 “中间操作”，即去重，去重的依据即为 Stream 序列元素类型的 equals 和 hashCode 方法，例如：

代码

1. //
2. // 获取商品名称，去重
3. //
4. void distinctGoodNames(List&lt;Good&gt; goods) {
5. goods.stream().map(Good::getName).distinct().forEach(System.out::println);
6. }

**sorted**

sorted 是 “中间操作”，以 Comparator&lt;? super T&gt; 作为参数，将 Stream 序列元素排序，Comparator&lt;? super T&gt;：

代码

1. //
2. // 商品按照价格升序排列
3. //
4. void sortGoods(List&lt;Good&gt; goods) {
5. goods.stream().sorted(Comparator.comparing(Good::getPrice)).forEach(System.out::println);
6. }

示例代码中，使用辅助方法 Comparator&lt;T&gt; comparing(Function&lt;? super T, ? extends U&gt;) 生成了 Comparator&lt;? super T&gt; 实例。

“内容介绍” 部分的 reversed()，同样是 Comparator&lt;T&gt; 的方法，并提供了默认实现，用于排序时，即可实现排序 “取反”。

**limit / skip**

limit / skip 是 “中间操作”，接收 long 类型的参数，实现 Stream 序列元素的截取和跳过：

代码

1. //
2. // 获得第 page 页的商品，每页商品数量为 page\_size
3. //
4. void listGoods(List&lt;Good&gt; goods, int page, int page\_size) {
5. goods.stream().skip((page - 1) * page\_size).limit(page).forEach(System.out::println);
6. }

**收集数据**

**count / min / max**  
count 是终止操作，将直接返回 Stream 的元素数量：

代码

1. //
2. // 获取高于指定价格的商品数量
3. //
4. long countGoodsOverPrice(List&lt;Good&gt; goods, long price) {
5. return goods.stream().filter(c -&gt; c.getPrice() &gt; price).count();
6. }

min / max，以 Comparator&lt;? super T&gt; 作为参数，返回最小值和最大值。对于原始类型 Stream，min / max 无参数，例如：

代码

1. //
2. // 获取最高的商品价格
3. //
4. OptionalLong maxGoodPrice(List&lt;Good&gt; goods) {
5. return goods.stream().mapToLong(Good::getPrice).max();
6. }

示例代码中，LongStream 的 max 方法返回类型为 OptionalLong，即为原始类型的 Optional&lt;T&gt;。

**reduce**

reduce，“归约”，是 “终止操作”，用于将 Stream 序列归约到一个具体的值，其声明，如下：

代码

01. //
02. // 提供初始值，以及两个 Stream 序列元素结合产生新值的方法
03. //
04. T reduce(T, BinaryOperator&lt;T&gt;);
05. //
06. // 提供两个 Stream 序列元素结合产生新值的方法，没有初始值，但通过 Optional&lt;T&gt; 避免 Stream 为空时返回 null
07. //
08. Optional&lt;T&gt; reduce(BinaryOperator&lt;T&gt;);
09. //
10. // 归约到新的类型：提供初始值，新值与 Stream 元素结合的方法，以及两个新值结合的方法
11. //
12. &lt;U&gt; U reduce(U, BiFunction&lt;U, ? super T, U&gt;, BinaryOperator&lt;U&gt;);

例如：

代码

1. long getTotalSalesAmount(List&lt;Good&gt; goods) {
2. //
3. // 获取 goods 集合的销售总额
4. //
5. return goods.stream().reduce(0L, (amount, good) -&gt; amount + good.getSales() * good.getPrice(),(left, right) -&gt; left + right);
6. }

或者：

代码

1. long getTotalSalesAmount(List&lt;Good&gt; goods) {
2. //
3. // 获取 goods 集合的销售总额
4. //
5. return goods.stream().mapToLong(c -&gt; c.getPrice() * c.getSales()).reduce(0, Long::sum);
6. }

**collect**

作为 “终止操作”，collect 即 “收集数据”。collect 以 “收集器” Collector&lt;? super T, A, R&gt; 作为参数，通常，我们使用 Collectors 提供的辅助函数获得 “收集器” 实例。

常用的辅助函数

**toList / toSet**      
    

代码

1. // // 获取商品名称的集合 // List&lt;String&gt;
2. &gt; getGoodNames(List&lt;Good&gt; goods) {   return
3. &gt; goods.stream().map(Good::getName).collect(Collectors.toList()); }
4. &gt;

toSet 与 toList 相似，但其返回结果为 Set。

**groupingBy**

代码

1. // // 将商品集合按照价格分组 // Map&lt;Long, List&lt;Good&gt;&gt;
2. &gt; groupGoodByPrice(List&lt;Good&gt; goods) {   return
3. &gt; goods.stream().collect(Collectors.groupingBy(Good::getPrice)); }
4. &gt;

     
**partitioningBy**

partitioningBy 与 groupingBy 类似，但其得到分组的键类型为 Boolean，即 true & false，最多两组：

代码

1. // // 根据是否超过指定销量将商品集合分组 // Map&lt;Boolean, List&lt;Good&gt;&gt;
2. &gt; partitionGoodWithSales(List&lt;Good&gt; goods, long sales) {   return
3. &gt; goods.stream().collect(Collectors.partitioningBy(c -&gt; c.getSales() &gt;=
4. &gt; sales)); }

     
**reducing**

Collectors.reducing 参数与 Stream.reduce 一致，其获得的 “收集器” 实例，作为 collect 参数，能够与 reduce 获得相同的结果。

根据是否需要存储中间状态，Stream 操作能够划分为 “无状态操作”、“有状态操作”。“无状态操作”，例如：filter、map；“有状态操作”，例如：limit、sorted 等，并且，对于 “有状态操作”，亦根据中间状态存储的要求，其区分 “有界”（例如：limit）、“无界”（例如：sorted）。

**并行**

通过 “并行 Stream” 即可获得 Stream API 的并行能力，例如：

代码

1. //
2. // 获取最高的商品价格
3. //
4. OptionalLong maxGoodPrice(List&lt;Good&gt; goods) {
5. return goods.stream().parallel().mapToLong(Good::getPrice).max();
6. }

代码所示，通过 Collection 接口的 parallelStream()、 BaseStream 接口的 parallel() 方法，都能够获得 “并行 Stream”。

并行 Stream 内部是基于 ForkJoinPool 模型获得并行能力，其默认线程数量即为通过 Runtime.getRuntime().availableProcessors() 获得的线程数。

不过，关于并行，两件事必须注意：一方面，正确性，避免 Stream 处理过程中共享可变状态；另一方面，务必记住，并行未必能够提高性能，通常适用于 Stream 元素数量大、或单个元素处理非常耗时的场景。

**写在最后**

请在阅读完本文后，尝试解答以下问题，最终的答案我们线上交流见 ^\_^

1\. 以下代码执行，将输出什么？

代码

1. String\[] words = { "a", "bb", "ccc", "dddd", "eeee" };
2. Arrays.stream(words).filter(c -&gt; { System.out.println(c); return true; }).limit(1).collect(Collectors.toList());

2\. 分别运用 Stream API 的 reduce、collect 方法实现以下方法：

代码

1. long getTotalSalesAmount(List&lt;Good&gt; goods) {
2. //
3. // 获取 goods 的销售总金额
4. //
5. }

3\. 通过 Stream API 实现以下方法：

代码

1. void printFibonacciSequence(int n) {
2. //
3. // 输出斐波那契数列的前 n 个数
4. //
5. }

4\. 通过 Stream API 改造以下代码： （提示，需要了解 collect 方法的参数类型

代码

01. Collector&lt;T, A, R&gt;）
02. class SaleRecord {
03. String recordId;  // 销售记录 Id
04. int goodId;       // 商品 Id
05. int promotionId; // 促销活动 Id
06. long price;       // 价格
07. long sales;       // 数量
08. }
09. class SalesAggregation {
10. int goodId;       // 商品 Id
11. int promotionId; // 促销活动 Id
12. long amount;     // 金额
13. }
14. //
15. // 聚合
16. //
17. List&lt;SalesAggregation&gt; aggregate(List&lt;SaleRecord&gt; saleRecords) {
18. Map&lt;String, SalesAggregation&gt; salesAggregations = new HashMap&lt;&gt;();
19. for (SaleRecord saleRecord : saleRecords) {
20. String key = String.format("%d\_%d", saleRecord.goodId, saleRecord.promotionId);
21. if (salesAggregations.containsKey(key)) {
22. salesAggregations.get(key).amount = salesAggregations.get(key).amount + saleRecord.price * saleRecord.sales;
23. } else {
24. SalesAggregation salesAggregation = new SalesAggregation();
25. salesAggregation.goodId = saleRecord.goodId;
26. salesAggregation.promotionId = saleRecord.promotionId;
27. salesAggregation.amount = saleRecord.price * saleRecord.sales;
28. salesAggregations.put(key, salesAggregation);
29. }
30. }
31. return new ArrayList&lt;&gt;(salesAggregations.values());

 

- [查看图片附件](http://www.iteye.com/news/32782)

来自: [gitbook](http://gitbook.cn/books/59ff3c278c83803b208e51e6/index.html?utm_source=iteyes)