You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Java Streams实现Map-Reduce范式的技术问询

一行Java Stream搞定订单数据的Map-Reduce

嘿,刚好能帮你解决这个问题!咱们直接针对订单列表的Map-Reduce需求来写一行优雅的Stream代码,先明确下常见的场景:按客户ID分组(Map阶段),然后计算每个客户有效订单的总金额(Reduce阶段)。这里默认有效订单是状态为"SUCCESS"的,你可以根据实际业务调整状态判断条件。

直接上代码:

Map<String, Integer> customerTotalValidAmount = customers.stream()
    .filter(c -> "SUCCESS".equals(c.getStatus())) // 过滤掉无效订单,按需保留
    .collect(Collectors.groupingBy(Customer::getCustId, Collectors.summingInt(Customer::getAmount)));

逻辑拆解(虽然是一行,但每一步都很清晰):

  • customers.stream():把订单列表转换成Stream流,开启链式操作
  • filter(...):先筛掉不符合要求的订单(比如取消、失败的),如果要统计所有订单,直接删掉这一步就行
  • collect(Collectors.groupingBy(...)):这就是核心的Map-Reduce操作:
    • Customer::getCustId:作为分组的Key,完成Map阶段——把订单按客户ID归类
    • Collectors.summingInt(Customer::getAmount):对每个客户的所有订单金额求和,完成Reduce阶段——聚合每组的数据

如果你的需求是统计每个客户的订单总数,只需要把summingInt换成counting():

Map<String, Long> customerOrderCount = customers.stream()
    .collect(Collectors.groupingBy(Customer::getCustId, Collectors.counting()));

小提醒:

  • 记得给Customer类补上对应的getter方法哦,不然Stream里的方法引用会报错:
    class Customer {
        String custId;
        String orderDate;
        String status;
        Integer amount;
        
        Customer(String custId, String orderDate, String status, Integer amount) {
            this.custId = custId;
            this.orderDate = orderDate;
            this.status = status;
            this.amount = amount;
        }
        
        // 必须的getter方法
        public String getCustId() { return custId; }
        public String getStatus() { return status; }
        public Integer getAmount() { return amount; }
    }
    
  • 如果订单金额可能为null,记得在filter里加上c.getAmount() != null,避免空指针异常~

内容的提问来源于stack exchange,提问作者merav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:35:49