stream流相关操作

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年又能改变什么?在我看来,一直在走正确的路,人是会出毛病的。

2023-10-30追加
List通过逗号合并成一个完成的String

String collect = sysDepts.stream().map(d -> d.getDeptId()).collect(Collectors.joining(","));

少时发愿不留家乡,以终生不得停歇为代价、四海为家、天地流浪。方得稍许慰藉。 起而四视,又当启程。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值