• 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);
    
    • 1
    • 2
    • 3

    方法二

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

    按照某个字段进行排序

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

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

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

    统计当年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);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

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

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

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

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

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

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

  • 相关阅读:
    matplotlib 文字标注(text、annotate)例程
    【Vue】使用 Composition API 开发TodoList(2)
    基于Python的性能优化
    LLaMA Factory单机微调的实战教程
    OpenCV3.4之VideoCapture分析
    常用注解归纳(二)
    SAP通过应用实例分析BOM组件中“Asm“勾选问题
    Django路由层解析
    form表单提交,jQuery对输入内容进行验证
    goland快捷键
  • 原文地址:https://blog.csdn.net/weixin_44685872/article/details/133999313