java8工具类Stream得用法
Stream 工具
Stream 是 Java 8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作。
当你使用 Stream 时,你会通过 3 个阶段来建立一个操作流水线。
# | 阶段 | 说明 |
---|---|---|
1 | 生成 | 创建一个 Stream 。 |
2 | 操作 | 在一个或多个步骤中,指定将初始 Stream 转换为另一个 Stream 的中间操作。 |
3 | 数据收集 | 使用一个终止操作来产生一个结果。该操作会强制它之前的延迟操作立即执行。 在这之后,该 Stream 就不会再被使用了。 |
例如:
String[] array = new String[]{"hello", "world", "goodbye"};
List<String> list = Arrays
.stream(array) // 1. 生成
.map(String::toUpperCase) // 2. 操作
.collect(Collectors.toList()); // 3. 数据收集
1. 生成:创建 Stream
有多种方式可以获得 Stream 对象:
-
方式 1:通过
Stream.of
方法用不定参参数列表创建 Stream 对象:
Stream<String> stream = Stream.of("...", "...", "...");
-
方式 2:通过
Stream.of
方法或Arrays.stream
方法用数组创建 Stream 对象:
String[] array = new String[]{"...", "...", "..."};
Stream<String> stream = Stream.of(array);
Stream<String> stream = Arrays.stream(array);
-
方式 3:通过
Collection#stream
方法或List#stream
方法或Set#stream
方法用集合创建 Stream 对象:
Collection<String> collection = ...;
List<String> list = ...;
Set<String> set = ...;
Stream<String> stream = collection.stream();
Stream<String> stream = list.stream();
Stream<String> stream = set.stream();
-
方法 4:通过
Stream.generate(Supplier)
方法配合Stream#limit
方法直接创建 Stream 对象,例如:
Stream<Double> stream = Stream.generate(Math::random).limit(10);
逻辑上,因为通过 Stream.generate
方法生成的 Stream 对象中的数据的数量是无限的(即,你向 Stream 对象每次『要』一个对象时它都会每次生成一个返回给你,从而达到『无限个』的效果),所以,会结合 Stream#limit
方法来限定 stream 流中的数据总量。
-
方法 5:通过
Stream.iterator(Final T, final UnaryOperator\<T> f)
方法配合Stream#limit
方法直接创建 Stream 对象,例如:
Stream<Integer> stream = Stream.iterate(1, n -> n += 2);
// 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, ...
Stream.iterator
方法要求你提供 2 个参数:
-
数据序列中的第一个数。这个数字需要使用者人为指定。通常也被称为『种子』。
-
根据『前一个数字』计算『下一个数字』的计算规则。
整个序列的值就是:x, f(x), f(f(x)), f(f(f(x))), ...
逻辑上,因为通过 Stream.iterator
方法生成的 Stream 对象中的数据的数量是无限的(即,你向 Stream 对象每次『要』一个对象时它都会每次生成一个返回给你,从而达到『无限个』的效果),所以,会结合 Stream#limit
方法来限定 stream 流中的数据总量。
2. 中间操作:处理 Stream 中的数据序列
所谓的中间操作,指的就是对 Stream 中的数据使用流转换方法。
Stream#filter
和 Stream#map
方法是 Stream 最常见的 2 个流转换方法。
2.1 Stream#filter 方法:筛选出 ...
Stream#filter
是过滤转换,它将产生一个新的流,其中「包含符合某个特定条件」的所有元素。逻辑上就是「选中、筛选出」的功能。
例如:
Stream<String> stream = Stream.of("hello", "world", "goodbye");
Stream<String> newStream = stream.filter( (item) -> item.startsWith("h") );
System.out.println( newStream.count() ); // 1
Stream#filter
方法的参数是一个 Predicate<T>
对象,用于描述「选中」规则。
2.2 Stream#map 方法:形变
我们经常需要对一个 Stream 中的值进行某种形式的转换。这是可以考虑使用 Stream#map
方法,并传递给它一个负责进行转换的函数。
例如:
newStream = stream.map(String::toUpperCase);
2.3 Stream#...Match 判断
Stream#anyMatch
、Stream#allMatch
、Stream#noneMatch
三个方法用于判断 Stream 中的元素是否『至少有一个』、『全部都』、『全部都不』满足某个条件。显而易见,这三个方法的返回值都是 boolean 值。
boolean b = stream.anyMatch((item) -> item.length() == 5);
3. 数据收集
当经过第 2 步的操作之后,你肯定会需要收集 Stream 中(特别是 newStream 中,即,经过处理)的数据。
-
收集方式 1:通过
Stream#toArray
方法收集到数组中:
Object[] array = newStream.toArray();
不过,无参的 Stream#toArray
方法返回的是一个 Object[]
数组。如果想获得一个正确类型的数组,可以将数组类型的构造函数传递给它:
String[] array = newStream.toArray(String[]::new); // 注意,这里是 String[] 而不是 String
-
收集方式 2:通过
Stream#collect
方法收集到集合中:
collection = stream.collect(Collectors.toCollection())
list = stream.collect(Collectors.toList());
set = stream.collect(Collectors.toSet())
上述 3 个方法是原始的 Stream#collect
方法的简化。因为原始的、最底层的 Stream#collect
方法看起来比较『奇怪』。所以,我们通常不会直接使用它,而是使用上述 3 个简写来间接使用。
-
收集方式 3:通过
Stream#collect
方法收集到 Map 中:
假设你有一个 Stream<Student>
,并且你想将其中的元素收集到一个 map 中,这样你随后可以通过他们的 ID 来进行查找。为了实现这个目的,你可以在 Stream#collect
方法中使用 Collectors.toMap
。
Collectors.toMap
有 2 个函数参数,分别用来生成 map 的 key 和 value。例如:
Map<Integer, String> map = stream.collect(
Collectors.toMap(Student::getId, Student::getName)
);
一般来说,Map 的 value 通常会是 Student 元素本身,这样的话可以实使用 Function.identity()
作为第 2 个参数,来实现这个效果(你可以将它视为固定用法)。
Map<Integer, Student> map = stream.collect(
Collectors.toMap(Student::getId, Function.identity())
);
4. Stream 的遍历访问
4.1 Stream#forEach 遍历
Stream#filter
方法会遍历 Stream 中的每一个元素,对 Stream 中的每一个元素做一个操作,至于做何种操作,取决于使用者传递给 Stream#filter
的方法的参数 Consumer 对象。
例如:
Stream<String> stream = Stream.of("hello", "world", "goodbye");
stream.forEach(System.out::println);
4.2 Stream#iterator 方法
Stream#iterator
方法会返回一个传统风格的迭代器,结合 Java SE 阶段的『集合框架』部分的知识点,通过 Iterator 对象你就可以遍历访问到 Stream 中的每一个元素。
newStream = ...;
Iterator<String> it = newStream.iterator();
while (it.hasNext()) {
String str = it.next();
System.out.println(str);
}
5. Stream#collect 的其它功能
Stream#collect
方法除了上述的「可以将 Stream 对象中的数据提取到集合对象中」之外,还有其它的更多更丰富的功能。
补充 Stream#collect
方法经常会用到 java.util.stream.Collectors
类内置的静态方法。
5.1 统计
Collectors 提供了一系列用于数据统计的静态方法:
# | 方法 |
---|---|
计数 | count |
平均值 | averagingInt / averagingLong / averagingDouble |
最值 | maxBy / minBy |
求和 | summingInt / summingLong / summingDouble |
统计以上所有 | summarizingInt / summarizingLong / summarizingDouble |
-
统计计数:
Stream#collect
利用Collectors.count
String[] strArray = new String[] {"hello", "world", "good", "bye"};
log.info("{}", Stream.of(strArray).collect(Collectors.counting()));
如果你使用的是 IDEA ,通过 IDEA 的只能代码提示,你会发现 Stream 对象中有一个上述代码的简化版的计数方法 count()
:
log.info("{}", Stream.of(arrays).count());
-
求平均值:
Stream#collect
利用Collectors.averagingX
String[] strArray = new String[] {"hello", "world", "good", "bye"};
log.info("{}", Stream.of(strArray).collect(Collectors.averagingInt(String::length)));
-
求极值:
Stream#collect
利用Collectors.maxBy
和Collectors.minBy
String[] strArray = new String[] {"hello", "world", "good", "bye"};
log.info("{}", Stream.of(strArray).collect(Collectors.maxBy((o1, o2) -> o1.length() - o2.length())));
log.info("{}", Stream.of(strArray).collect(Collectors.minBy((o1, o2) -> o1.length() - o2.length())));
通过 IDEA 的代码提示功能,你会发现,上述代码有很大的简化空间:
// 保留 collect 方法和 Collectors 方法的前提下,可以简化成如下
log.info("{}", Stream.of(strArray).collect(Collectors.maxBy(Comparator.comparingInt(String::length))));
log.info("{}", Stream.of(strArray).collect(Collectors.minBy(Comparator.comparingInt(String::length))));
// 不保留 collect 方法和 Collectors 方法的情况下,可以进一步简化
log.info("{}", Stream.of(strArray).max(Comparator.comparingInt(String::length)));
log.info("{}", Stream.of(strArray).min(Comparator.comparingInt(String::length)));
-
统计求和:
Stream#collect
利用Collectors.summingX
进行统计求和
log.info("{}", Stream.of(strArray).collect(Collectors.summingInt(String::length)));
通过 IDEA 的代码提示功能,你会发现,上述代码可以简化:
log.info("{}", Stream.of(strArray).mapToInt(String::length).sum());
-
一次性批量统计上述信息:
Stream#collect
利用Collectors.summarizingX
进行统计
Stream#collect
结合 Collectors.summarizingX
可以返回一个 XxxSummaryStatistics 对象,其中包含了上述的统计计数、平均值、极值等多项数据:
String[] strArray = new String[] {"hello", "world", "good", "bye"};
IntSummaryStatistics statistics = Stream.of(strArray).collect(Collectors.summarizingInt(String::length));
log.info("{}", statistics);
log.info("{}", statistics.getCount());
log.info("{}", statistics.getSum());
log.info("{}", statistics.getMin());
log.info("{}", statistics.getMax());
log.info("{}", statistics.getAverage());
5.2 分组
Stream#collect
利用 Collectors.partitioningBy
方法或 Collectors#groupingBy
方法可以将 Stream 对象中的元素「按照你所提供的规则」分别提取到两个不同的 List 中。
String[] strArray = new String[] {"hello", "world", "good", "bye"};
log.info("{}", Stream.of(strArray).collect(Collectors.groupingBy(s -> s.length() % 2 == 0)));
log.info("{}", Stream.of(strArray).collect(Collectors.partitioningBy(s -> s.length() % 2 == 0)));
这两个方法返回的都是 Map<Boolean, List<T>>
对象,因此,你可以以 true
或 false
为键,分别从中拿到其中的某一部分数据。
另外,你可以连续多次分组,只需要嵌套使用 Collectors.groupingBy
或 CollectorspartitiongBy
方法。
String[] strArray = new String[] {"hello", "world", "good", "bye"};
log.info("{}", Stream.of(strArray).collect(
Collectors.partitioningBy(s -> s.length() % 2 == 0,
Collectors.partitioningBy(s -> s.length() > 3)
)));
log.info("{}", Stream.of(strArray).collect(
Collectors.groupingBy(s -> s.length() % 2 == 0,
Collectors.groupingBy(s -> s.length() > 3)
)));
5.3 拼接字符串
Stream#collect
利用 Collectors.joining
方法可以将 stream 中的元素用「你所指定的」连接符(没有的话,则直接拼接)拼接成一个字符串。
String[] strArray = new String[] {"hello", "world", "good", "bye"};
log.info("{}", Stream.of(strArray).collect(Collectors.joining()));
log.info("{}", Stream.of(strArray).collect(Collectors.joining("-")));
6. 排序:Stream#sorted 方法
Stream#sorted
方法能实现对 stream 中的元素的排序。
它有两种排序:
-
Stream#sorted()
:自然排序,流中元素需实现 Comparable 接口 -
Stream#sorted(Comparator com)
:Comparator 排序器自定义排序
String[] strArray = new String[] {"hello", "world", "good", "bye"};
log.info("{}", Stream.of(strArray).sorted().collect(Collectors.toList()));
log.info("{}", Stream.of(strArray).sorted(Comparator.comparingInt(o -> o.charAt(1))).collect(Collectors.toList()));
log.info("{}", Stream.of(strArray).sorted(Comparator
.comparingInt(String::length) // 先以字符串长度排序
.thenComparingInt(value -> value.charAt(value.length()-1)) // 再以字符串最后一个字符大小排序
).collect(Collectors.toList()));
7. 提取/组合
流也可以进行合并、去重、限定、跳过等操作。
7.1 合并和去重
流的合并使用 Stream.concat
方法;对流中的元素去重则使用 Stream#distinct
方法。
Stream<String> stream1 = Stream.of("a", "b", "c", "d");
Stream<String> stream2 = Stream.of("c", "d", "e", "f");
log.info("{}", Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()));
7.2 限定和跳过
限定指的是只从流中取出前 N 个数据以生成新的流对象,使用 Stream#limit
方法;跳过指的是忽略流中的前 N 个数据,取剩下的数据以生成新的流对象,使用 Stream#skip
方法。
Stream<String> stream1 = Stream.of("a", "b", "c", "d");
Stream<String> stream2 = Stream.of("c", "d", "e", "f");
log.info("{}", stream1.limit(2).collect(Collectors.toList()));
log.info("{}", stream2.skip(2).collect(Collectors.toList()));
8.举例说明
@SpringBootTest
class EmployeeTest {
@Resource
private EmployeeDao dao;
private static List<EmployeePo> poList;
@Test // 部门2中的员工的最高工资的那个人的名字
public void homework() {
EmployeePo employeePo = poList.stream().filter(po -> po.getDepartmentId() == 2)
.max((left, right) -> left.getSalary() < right.getSalary() ? -1 : 0)
.get();
System.out.println(employeePo.getName());
}
@Test // select average(salary) from employee where department_id = 2;
public void countAverageSalaryOfDepartment() {
Double collect = poList.stream()
.filter(po -> po.getDepartmentId() == 2)
.collect(Collectors.averagingDouble(EmployeePo::getSalary));
System.out.println(collect);
}
@Test // select sum(department_id) from employee where department_id = ?
public void countSumOfDepartment() {
Long collect = poList.stream()
.filter(employeePo -> employeePo.getDepartmentId() == 2)
.count();
System.out.println(collect);
}
@Test // select average(salary) where employee
public void countAverageSalary() {
// 1. 创佳 Stream 对象
Stream<EmployeePo> stream = poList.stream();
// 2. 操作 Stream 对象(这个过程中,可能会创建出新的 Stream 对象)
// 3. 将 Stream 对象中的数据收集到 Array、Collection、Set 中。
Double collect = stream.collect(Collectors.averagingDouble(EmployeePo::getSalary));
System.out.println(collect);
}
@Test // select min(salary) where employee
public void countMinSalary() {
Stream<EmployeePo> stream = poList.stream();
// Optional<EmployeePo> min = stream.min((left, right) -> left.getSalary() < right.getSalary() ? -1 : 1);
// System.out.println(min.get());
Optional<EmployeePo> min = stream.max((left, right) -> left.getSalary() < right.getSalary() ? 1 : -1);
System.out.println(min.get());
}
@Test // select max(salary) where employee
public void countMaxSalary() {
// 1. 创佳 Stream 对象
Stream<EmployeePo> stream = poList.stream();
// 2. 操作 Stream 对象(这个过程中,可能会创建出新的 Stream 对象)
// 3. 将 Stream 对象中的数据收集到 Array、Collection、Set 中。
Optional<EmployeePo> max = stream.max((left, right) -> left.getSalary() < right.getSalary() ? -1 : 1);
System.out.println(max.get());
}
@Test // select * from employee where salary > ? and commission is not null
public void selectBySalaryGtAndCommissonNotNull() {
/*
List<EmployeePo> collect = poList.stream() // 1
.filter(employeePo -> employeePo.getSalary() > 1500) // 2
.filter(employeePo -> employeePo.getCommission() != null) // 2
.collect(Collectors.toList()); // 3
*/
List<EmployeePo> collect = poList.stream() // 1
.filter(employeePo -> employeePo.getSalary() > 1500 && employeePo.getCommission() != null) // 2
.collect(Collectors.toList()); // 3
System.out.println(collect);
}
@Test // select * from employee where department_id = ?
public void selectByDepartmentId() {
List<EmployeePo> collect = poList.stream() // 1
.filter(employeePo -> employeePo.getDepartmentId() == 1) // 2
.collect(Collectors.toList()); // 3
System.out.println(collect);
}
@Test // select * from employee where name = ?
public void selectByName() {
List<EmployeePo> result = poList.stream() // 1. 创佳 Stream 对象
.filter(employeePo -> "KING".equals(employeePo.getName())) // 2. 操作 Stream 对象(这个过程中,可能会创建出新的 Stream 对象)
.collect(Collectors.toList()); // 3. 将 Stream 对象中的数据收集到 Array、Collection、Set 中。
System.out.println(result);
}
@Test // select * from employee where id = ?
public void selectById() {
/*
// 1. 获得一个 stream 对象
Stream<EmployeePo> stream = poList.stream();
// 2. 对流中的数据进行处理
Stream<EmployeePo> stream1 = stream.filter(new Predicate<EmployeePo>() {
@Override
public boolean test(EmployeePo po) {
return po.getId() == 1;
}
});
// 3. 将 stream 中的数据收集到 Array、Collection、Set 中。
List<EmployeePo> collect = stream1.collect(Collectors.toList());
System.out.println(collect);
*/
List<EmployeePo> collect = poList.stream() // 1. 获得一个 stream 对象
.filter(po -> po.getId() == 1) // 2. 对流中的数据进行处理
.collect(Collectors.toList()); // 3. 将 stream 中的数据收集到 Array、Collection、Set 中。
System.out.println(collect);
}
@BeforeEach
public void before() {
poList = dao.selectList(null);
}
}