当前位置:首页 > 编程笔记 > 正文
已解决

stream流相关操作

来自网友在路上 144844提问 提问时间:2023-10-24 04:59:05阅读次数: 44

最佳答案 问答题库448位专家为你答疑解惑

stream真的没有什么好说的,filter、map这俩常用的程序可以说每天都要写好几遍,那么问题来了,为什么还要拿出来讲讲呢?当然不可能是因为想要划水,主要是工作中它的其他相关方法也有不少涉及。以下是按照不同需求涉及到的方法。

统计list中某个字段的总和

方法一

BigDecimal sum=jsonObjects.stream()
.filter(d-> childIds1.indexOf(d.getLong("subarea_id"))!=-1).map(d->d.getBigDecimal("result")).reduce(BigDecimal.ZERO, BigDecimal::add);

方法二

double planValue = maps.stream()
.mapToDouble(d ->Double.valueOf(d.get("plan_value").toString())).sum();
Integer chargeTotalLevel = chargingPileList.stream().mapToInt(LowVoltageChargePile::getLevel).sum();

按照某个字段进行排序

 List<Person> sortedPeople = people.stream().sorted(Comparator.comparing(Person::getAge)).sorted(Comparator.reverseOrder()).collect(Collectors.toList());

统计满足某个条件的集合子元素数目

long count = jsonObjects.stream()
.map(jsonObj -> jsonObj.getLong("father_id"))
.filter(id -> childIds1.contains(id))
.count();

统计当年12个月中的value,但是hcPowerStatistics未必有12个

//原本是有数据的,这里随便搞一下
List<Map<String, Object>> hcPowerStatistics=new ArrayList<>();
Map<String, Map<String, Object>> hcPowerMap = hcPowerStatistics.stream().collect(Collectors.toMap(d -> d.get("month").toString(), Function.identity()));for (int month = 1; month <= 12; month++) {String monthString = String.format("%02d", month);String yearMonth = year + "-" + monthString;Map<String, Object> filterList = hcPowerMap.get(yearMonth);double power = (filterList != null) ? (double) filterList.get("total_value") : 0;powerList.add(power);
}

list根据筛选条件,确定只有一条数据的情况下

Integer result = numbers.stream().filter(number -> number > 5) // 筛选条件.findFirst() // 获取第一个满足条件的对象.orElse(0); // 如果不存在满足条件的对象,则返回默认值0

我不清楚现在为什么要戒烟,戒烟能带给我什么好处呢?让我有套上枷锁、给人当牛做马的资格?多活10年又能改变什么?在我看来,一直在走正确的路,人是会出毛病的。

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"stream流相关操作":http://eshow365.cn/6-23001-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!