Java知识点|Stream流
快速简单学习使用Java8提供的新特性:Stream。
一、了解Stream内部的基本流程
1.1、流的中间操作
1.1.1、筛选与切片
- filter:过滤流中某些元素
- limit(n):获取n个元素
- skip(n):跳过n元素
- distinct:通过流中元素的hashCode和equals去除重复的元素
1.1.2、映射
- map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
1.1.3、排序
- sorted:自然排序,流中元素需实现Comparable接口
- sorted(Comparator com):定制排序,自定义Comparator排序器
1.2、流的终止操作
1.2.1、匹配、聚合操作
- a l lMatch:
- noneMatch:
- anyMatch:
- findFirst:返回流中第一个元素
- findAny:返回流中的任意元素
- count:返回流中元素的总个数
- max:返回流中最大的元素
- min:返回流中最小的元素
二、Stream实例说明
问:java列表对象, 需要对某一个字段进行排序,但是这个字段里面有一些会存在空值的情况。处理代码如下:
batches.sort(
Comparator.comparing(TCutBatch::getDaySeq,Comparator.nullsFirst(Integer::compareTo))
.thenComparing(TCutBatch::getCreateTime)
.reversed());
Compartor.comparing(TCutBatch::getDaySeq)
对dayseq字段进行排序,Compartor.nullsFirst(Integer::compareTo)
表示如果有空值的话就放到列表的首位; .themComparing(TCutBatch::getCreateTime)
先根据dayseq排序,在根据createTime排序,最后在反转数据。
问:java列表转字典的时候,如果存在相同的key的话,就会出现多个value值的报错。
处理这个问题一般有三种方式,一个是用那个值,第二个就是将所有值进行合并, 第三个就是value用列表来存。
reportSegmentCells.stream().collect(Collectors.toMap(
TReportSegmentCell::getCellId, Function.identity(), (v1,v2)->{return v1;}
));
(v1,v2)->{retur v1;}
表示用前值;(v1,v2
)->{return v2;}`就表示用后值覆盖前值。
问:从对象列表中获取到某个属性集合,并去重
List<Long> equModelIdList = equList.stream()
.map(TEqu::getEquModelId).distinct().collect(Collectors.toList());
// .map() 获取到所有的属性值
// .distinct() 去重
// .collect() 转成对应结构
问:获取数组的最小值,获取数组不同值的个数
int min = Arrays.stream(nums).min().getAsInt();
int distinceCount = (int) Arrays.stream(nums).distinct().count();
Changelog
4/28/25, 12:53 PM
View All Changelog
d7ec9
-on