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

如何使用Java Stream API对OrderItems列表分组并转换为NewOrderItems

使用Java Stream API分组并转换OrderItems集合

需求说明

需要将OrderItems列表按id和portion进行分组,统计每组的元素数量(对应NewOrderItems的amount字段),最终转换为NewOrderItems实例的集合。

实现步骤与代码

首先为两个实体类补充构造器(方便实例化):

public class OrderItems {
    public int id;
    public double portion;

    public OrderItems(int id, double portion) {
        this.id = id;
        this.portion = portion;
    }
}

public class NewOrderItems {
    public int id;
    public double portion;
    public long amount;

    public NewOrderItems(int id, double portion, long amount) {
        this.id = id;
        this.portion = portion;
        this.amount = amount;
    }

    @Override
    public String toString() {
        return "NewOrderItems{id=" + id + ", portion=" + portion + ", amount=" + amount + "}";
    }
}

核心Stream处理逻辑:

import java.util.ArrayList;
import java.util.AbstractMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<OrderItems> orderItems = new ArrayList<>();
        orderItems.add(new OrderItems(1, 0.5));
        orderItems.add(new OrderItems(2, 1));
        orderItems.add(new OrderItems(1, 0.5));
        orderItems.add(new OrderItems(1, 1.5));
        orderItems.add(new OrderItems(2, 1));
        orderItems.add(new OrderItems(2, 0.5));

        List<NewOrderItems> result = orderItems.stream()
                // 按id和portion复合分组,统计每组元素数量
                .collect(Collectors.groupingBy(
                        item -> new AbstractMap.SimpleEntry<>(item.id, item.portion),
                        Collectors.counting()
                ))
                // 将分组结果转换为NewOrderItems集合
                .entrySet().stream()
                .map(entry -> {
                    Map.Entry<Integer, Double> key = entry.getKey();
                    return new NewOrderItems(key.getKey(), key.getValue(), entry.getValue());
                })
                .collect(Collectors.toList());

        // 输出结果
        result.forEach(System.out::println);
    }
}

代码关键点解析

  • 复合分组键:用AbstractMap.SimpleEntry把id和portion组合成统一键,确保只有id和portion完全相同的元素才会被分到同一组。
  • 数量统计:Collectors.counting()直接统计每组内的元素个数,对应NewOrderItems的amount字段。
  • 类型转换:遍历分组后的键值对,把键中的id、portion和值中的统计数量映射为NewOrderItems实例,最终收集为目标列表。

运行结果

NewOrderItems{id=1, portion=0.5, amount=2}
NewOrderItems{id=1, portion=1.5, amount=1}
NewOrderItems{id=2, portion=0.5, amount=1}
NewOrderItems{id=2, portion=1.0, amount=2}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:20:21