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

如何用Java Stream API将List<T>按order分组排序后转为List<List<T>>

问题解答

完全可以通过Java Stream API实现该需求。

前提说明

假设类T已经正确实现了三个属性的getter方法:getValue()、getPosition()、getOrder(),对应三个属性的读取。

实现代码

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// T类示例定义
class T {
    private int value;
    private int position;
    private int order;

    public T(int value, int position, int order) {
        this.value = value;
        this.position = position;
        this.order = order;
    }

    public int getValue() {
        return value;
    }

    public int getPosition() {
        return position;
    }

    public int getOrder() {
        return order;
    }

    @Override
    public String toString() {
        return "(" + value + "," + position + "," + order + ")";
    }
}

public class StreamGroupSortDemo {
    public static void main(String[] args) {
        List<T> input = List.of(
                new T(1, 1, 1),
                new T(1, 2, 2),
                new T(1, 3, 1),
                new T(3, 2, 3),
                new T(5, 1, 2),
                new T(3, 2, 1)
        );

        List<List<T>> output = input.stream()
                // 按order属性分组
                .collect(Collectors.groupingBy(
                        T::getOrder,
                        // 分组后组内按position升序排序
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                groupList -> groupList.stream()
                                        .sorted(Comparator.comparingInt(T::getPosition))
                                        .toList()
                        )
                ))
                // 按order值升序排列外层列表
                .entrySet()
                .stream()
                .sorted(Comparator.comparingInt(Map.Entry::getKey))
                .map(Map.Entry::getValue)
                .toList();

        // 验证输出
        output.forEach(System.out::println);
    }
}

逻辑说明

  1. 调用Collectors.groupingBy方法,指定分组键为T::getOrder,完成按order属性分组的核心逻辑
  2. 通过Collectors.collectingAndThen实现分组后处理:先将同组元素收集为临时List,再转流按position属性升序排序,最终生成组内有序的List
  3. 由于默认分组使用的HashMap是无序的,所以需要将分组结果的Entry按key(即order值)升序排序,提取value后收集为最终的嵌套List,保证外层列表顺序和order值升序一致,完全匹配预期输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:09:03