lambda表达式与流优化代码

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值