当前位置:网站首页>lambda表达式与流优化代码
lambda表达式与流优化代码
2022-06-12 21:32:00 【NGC73】
lambda表达式与流优化代码
1 代码应用示例
java8以前对集合进行排序用得比较多的,比如需要按照某个集合的时间对集合进行排序
Collections.sort(payList, new Comparator<ErpContractPay>() {
@Override
public int compare(ErpContractPay o1, ErpContractPay o2) {
System.out.println(o1);
Date payTime1 = o1.getPayTime();
Date payTime2 = o2.getPayTime();
//先判断是否为空
if(payTime1==null||payTime2==null){
throw new RuntimeException("存在空时间,无法比较");
}else{
return payTime1.compareTo(payTime2);
}
}
});
java8以后的新特性实现,代码变得清晰明了,易于阅读。
private List sortPayTime(List payList) {
return payList.stream()
.sorted(comparing(ErpContractPay::getPayTime)) //根据支付时间进行排序
.collect(Collectors.toList()); //转换为List
}
亦比如对加载字典缓存进行排序
Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()){
DictUtils.setDictCache( entry.getKey(),
entry.getValue().
stream().
sorted(Comparator.comparing(SysDictData::getDictSort)).
collect(Collectors.toList()));
}
java17新特性对stream进一步优化,如果需要将Stream转换成List,需要通过调用collect方法使用Collectors.toList(),代码非常冗长。在Java 17中将会变得简单,可以直接调用toList()。
Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()){
DictUtils.setDictCache( entry.getKey(),
entry.getValue().
stream().
sorted(Comparator.comparing(SysDictData::getDictSort)).
toList();
}
2 流的使用
流的使用将分为终端操作和中间操作进行介绍
2.1 中间操作
2.1.1 filter 筛选
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().filter(i -> i > 3);
通过使用 filter 方法进行条件筛选,filter 的方法参数为一个条件
2.1.2 distinct 去除重复元素
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().distinct();
通过 distinct 方法快速去除重复的元素
2.1.3 limit 返回指定流个数
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().limit(3);
通过 limit 方法指定返回流的个数,limit 的参数值必须 >=0,否则将会抛出异常
2.1.4 skip 跳过流中的元素
List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().skip(2);
通过 skip 方法跳过流中的元素,上述例子跳过前两个元素,所以打印结果为 2,3,4,5,skip 的参数值必须 >=0,否则将会抛出异常
2.1.5 map 流映射
所谓流映射就是将接受的元素映射成另外一个元素
List stringList = Arrays.asList(“Java 8”, “Lambdas”, “In”, “Action”);
Stream stream = stringList.stream().map(String::length);
2.1.6 复制代码
通过 map 方法可以完成映射,该例子完成中 String -> Integer 的映射,之前上面的例子通过 map 方法完成了 Dish->String 的映射
2.1.7 flatMap 流转换
将一个流中的每个值都转换为另一个流
List wordList = Arrays.asList(“Hello”, “World”);
List strList = wordList.stream()
.map(w -> w.split(" “))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
map(w -> w.split(” ")) 的返回值为 Stream<String[]>,我们想获取 Stream,可以通过 flatMap 方法完成 Stream ->Stream 的转换
2.1.8 元素匹配
提供了三种匹配方式:
1.allMatch 匹配所有
List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
System.out.println(“值都大于3”);
}
2.anyMatch 匹配其中一个
List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().anyMatch(i -> i > 3)) {
System.out.println(“存在大于3的值”);
}
等同于
for (Integer i : integerList) {
if (i > 3) {
System.out.println(“存在大于3的值”);
break;
}
}
3.noneMatch 全部不匹配
List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
System.out.println(“值都小于3”);
}
2.2 终端操作
2.2.1 统计流中元素个数
通过 count
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();
通过使用 count 方法统计出流中元素个数
通过 counting
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());
最后一种统计元素个数的方法在与 collect 联合使用的时候特别有用
2.2.2 查找
提供了两种查找方式
findFirst 查找第一个
//查找到第一个大于 3 的元素并打印
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional result = integerList.stream().filter(i -> i > 3).findFirst();
findAny 随机查找一个
List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional result = integerList.stream().filter(i -> i > 3).findAny();
通过 findAny 方法查找到其中一个大于三的元素并打印,因为内部进行优化的原因,当找到第一个满足大于三的元素时就结束,该方法结果和 findFirst 方法结果一样。提供 findAny 方法是为了更好的利用并行流,findFirst 方法在并行上限制更多
2.2.3 reduce 将流中的元素组合起来
假设我们对一个集合中的值进行求和
JDK8 之前:
int sum = 0;
for (int i : integerList) {
sum += i;
}
JDK8 之后通过 reduce 进行处理
int sum = integerList.stream().reduce(0, (a, b) -> (a + b));
一行就可以完成,还可以使用方法引用简写成:
int sum = integerList.stream().reduce(0, Integer::sum);
reduce 接受两个参数,一个初始值这里是 0,一个 BinaryOperator accumulator 来将两个元素结合起来产生一个新值,
另外, reduce 方法还有一个没有初始化值的重载方法
2.2.4 获取流中最小最大值
通过 min/max 获取最小最大值
Optional min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional max = menu.stream().map(Dish::getCalories).max(Integer::compareTo);
也可以写成:
OptionalInt min = menu.stream().mapToInt(Dish::getCalories).min();
OptionalInt max = menu.stream().mapToInt(Dish::getCalories).max();
min 获取流中最小值,max 获取流中最大值,方法参数为 Comparator<? super T> comparator
通过 minBy/maxBy 获取最小最大值
Optional min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optional max = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));
minBy 获取流中最小值,maxBy 获取流中最大值,方法参数为 Comparator<? super T> comparator
通过 reduce 获取最小最大值
Optional min = menu.stream().map(Dish::getCalories).reduce(Integer::min);
Optional max = menu.stream().map(Dish::getCalories).reduce(Integer::max);
参考文章:
https://libin9ioak.blog.csdn.net/article/details/122174470?spm=1001.2014.3001.5502
https://blog.csdn.net/u014231523/article/details/102535902
边栏推荐
- Graphics2D类基本使用
- SQL调优指南笔记13:Gathering Optimizer Statistics
- Graphics2d class basic use
- ZGC concurrent identity and multi view address mapping in concurrent transition phase
- GNS installation and configuration
- SQL调优指南笔记17:Importing and Exporting Optimizer Statistics
- Distributed cloud service developer'allegro Xile technology 'received an angel round financing of US $3million
- USB mechanical keyboard changed to Bluetooth Keyboard
- 测试基础之:单元测试
- selenium操作元素遇到的异常
猜你喜欢

SQL调优指南笔记14:Managing Extended Statistics

如何自己动手写一个vscode插件,实现插件自由!

torch. Finfo function

torch. nn. Linear() function

Lintcode:127. Topology sorting

Kdd2022 | graphmae: self supervised mask map self encoder

Turing prize winner: what should I pay attention to if I want to succeed in my academic career?

SQL调优指南笔记11:Histograms

利用ADG Standby克隆PDB

ICML2022 | GALAXY:极化图主动学习
随机推荐
selenium操作元素遇到的异常
Smart management of green agriculture: a visual platform for agricultural product scheduling
SQL调优指南笔记11:Histograms
Npoi create word
如何自己动手写一个vscode插件,实现插件自由!
SQL调优指南笔记15:Controlling the Use of Optimizer Statistics
风控建模十:传统建模方法存在的问题探讨及改进方法探索
测试基础之:单元测试
A high-value MySQL management tool
zgc的垃圾收集的主要階段
Introduction to the characteristics of balancer decentralized exchange market capitalization robot
JUC并发工具包使用指南
Lombok package is successfully installed, but the runtime prompts that get, set method and constructor solution cannot be found
Compiling process of OpenSSL and libevent on PC
选择排序
重排数列练习题
Limit of advanced mathematics
SQL调优指南笔记18:Analyzing Statistics Using Optimizer Statistics Advisor
Sorting out the knowledge points of primary and secondary indicators
SQL调优指南笔记10:Optimizer Statistics Concepts