java8新特性,stream流多种写法
1.stream的.filter().findAny().orElse (null) 是什么意思EventStatisticsVo eventStatisticsVoTotal = list.stream().filter(p -> p.getType() == 2).findAny().orElse(eventStatisticsVoT);filter(p -> p.getType(
1.stream的.filter().findAny().orElse (null) 是什么意思
EventStatisticsVo eventStatisticsVoTotal = list.stream().filter(p -> p.getType() == 2).findAny().orElse(eventStatisticsVoT);
filter(p -> p.getType() == 2)表示过滤出list中type为2的元素;
.findAny()表示将其中任意一个返回;
.orElse(null)表示如果一个都没找到返回null
2.list.stream().collect(Collectors.groupingBy(Strategy::getStrategyTypeId))
Map<Long, List<Strategy>> map = list.stream().collect(Collectors.groupingBy(Strategy::getStrategyTypeId));
以上写法的意思是将list中的元素,按照StrategyTypeId这个属性分组,相同的为一组,最后封装成map集合,集合中StrategyTypeId属性为key,具有相同StrategyTypeId的元素集合为value。
3.list.stream().map(p-> p.setScores("333") ).collect(Collectors.toList());
list.stream().map(p->{
p.setScores("333");
return p;
}).collect(Collectors.toList());
map 方法用于映射每个元素到对应的结果,以上两段代码片段使用 map 为每个元素设置了scores,第二种写法可为元素进行多个操作;
4.list.stream().max(Comparator.comparing(ArchivesJsonVo::getTime)).get();
list.stream().min(Comparator.comparing(ArchivesJsonVo::getTime)).get();
以上代码片段用于获取集合中,time属性最大和最小得元素
5.list.stream().sorted(Comparator.comparing(ArchivesJsonVo::getTime)).collect(Collectors.toList()); //返回list集合以time属性升序排序 --默认升序
list.stream().sorted(Comparator.comparing(ArchivesJsonVo::getTime).reversed()).collect(Collectors.toList()); //返回list集合以time属性降序排序
list.stream().sorted(Comparator.comparing(ArchivesJsonVo::getTime).thenComparing(ArchivesJsonVo::getRatio)).collect(Collectors.toList()); //返回list集合以time属性升序排序,再以ratio属性升序
list.stream().sorted(Comparator.comparing(ArchivesJsonVo::getTime,Comparator.reverseOrder()).thenComparing(ArchivesJsonVo::getRatio)).collect(Collectors.toList()); //返回list集合以time属性降序排序,再以ratio属性升序
以上代码用于对集合中元素根据某个属性进行排序
6.如何对集合中得元素按照某元素去重呢?
List<SearchVisitorVo> list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(SearchVisitorVo::getIdCard))), ArrayList::new));
以上代码片段是对集合中元素,按照IdCard属性去重
7.如何对集合求并集?
List<Integer> allFaceIds=new ArrayList<>();
allFaceIds.addAll(blackFaceIds);
allFaceIds.addAll(visitFaceIds);
allFaceIds.addAll(custodyFaceIds);
//求并集
allFaceIds = allFaceIds.stream().distinct().collect(Collectors.toList());
8.如何对集合求交集?
List<Integer> visitFaceIds=new ArrayList<>();
List<Integer> blackFaceIds=new ArrayList<>();
//求交集
List<Integer> list=visitFaceIds.stream().filter(x->blackFaceIds.contains(x)).collect(Collectors.toList());
9.筛选与切片
filter:过滤流中的某些元素
limit(n):获取n个元素
skip(n):跳过n元素,配合limit(n)可实现分页
distinct:通过流中元素的 hashCode() 和 equals() 去除重复元素
Stream<Integer> stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14);
Stream<Integer> newStream = stream.filter(s -> s > 5) //6 6 7 9 8 10 12 14 14
.distinct() //6 7 9 8 10 12 14
.skip(2) //9 8 10 12 14
.limit(2); //9 8
更多推荐
所有评论(0)