Java8 Lambda表达式,常用接口,Stream流式处理
java8 stream 源码分析
java8 lambda底层原理
.
Lambda 表达式 — Oracle 官方文档 — Lambda Expressions 2022-07-16 18:00:29
Lambda 表达式 方法引用 — Oracle 官方文档 — Method References 2022-07-16 18:05:41
Lambda
Lambda表达式
函数式接口
1 | 函数式接口:有且只有一个抽象方法的接口,称之为函数式接口 |
基本语法
()->{}
1 | 1. `()`参数,参数声明可以省略 |
日志优化案例
使用场景
作为方法参数
作为方法返回值
对象名引用成员方法
类名引用静态方法
super引用父类方法
this引用本类方法
类构造器引用
数组构造器引用
常用接口
Supplier
提供者
1 |
|
Consumer
消费者
1 |
|
Predicate
布尔值函数
1 |
|
Function
类型转换函数
1 |
|
Stream
Stream流式处理
思想
流式思想
所以流只能被消费一次。再次使用会有异常。请见异常案例
获取
获取Stream流
1 | java.util.stream.Stream<T>是Java 8新加入的最常用的流接口。(这并不是一个函数式接口。) |
forEach
循环
filter
过滤
map
映射
flatMap
将流展开(看下面例子:将一个 list 中的 subList 进行合并)
2021-11-12 16:00:52 补充
1 | List<List<Integer>> list = new ArrayList<>(); |
count
统计
limit
限制
skip
跳过
concat
合并
distinct
去重
max
最大值
min
最小值
average
平均值
sum
求和
reduce
归约
2021-11-06 00:56:40
1 | List<BigDecimal> list = new ArrayList<>(Arrays.asList(1.1, 2.2, 3.3)).stream().map(BigDecimal::valueOf).collect(Collectors.toList()); |
sorted
排序
2021-11-12 16:50:45
1 | List<Integer> list = Arrays.asList(22, 11, 33); |
toList
collect转List
collect
收集
2021-11-12 17:31:43
1 | List<String> list = Arrays.asList("b", "c", "a"); |
toMap
collect转Map
1 | public class Person |
groupingBy
分组
1 | /*按照年龄分组*/ |