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

如何基于内部List<Integer>的第二个元素排序List<List<Integer>>?

如何用Java Streams对List<List>按内部列表的第二个元素排序?

嘿,这个需求用Java Streams完全可以优雅搞定!我来给你一步步拆解,顺便附上能直接运行的代码示例~

核心思路

要实现按每个内部List<Integer>的第二个元素排序,关键是在Stream的sorted()方法里指定自定义比较规则:告诉程序提取每个内部列表的第二个元素(注意Java列表索引从0开始,所以第二个元素的索引是1)作为排序依据。

完整代码实现

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

public class NestedListSortExample {
    public static void main(String[] args) {
        // 你的原始输入集合
        List<List<Integer>> originalList = List.of(
            List.of(5, 3, 6, 7),
            List.of(2, 1, 6, 3),
            List.of(3, 2, 6, 3),
            List.of(5, 4, 4, 3)
        );

        // 用Streams完成排序
        List<List<Integer>> sortedList = originalList.stream()
            // 核心:按内部列表的第二个元素升序排序
            .sorted(Comparator.comparing(innerList -> innerList.get(1)))
            // 将排序后的流转换为List
            .collect(Collectors.toList());

        // 打印验证结果
        sortedList.forEach(System.out::println);
    }
}

代码细节解释

  • originalList.stream():把原始集合转为Stream,开启流式操作的入口。
  • .sorted(Comparator.comparing(innerList -> innerList.get(1))):这是实现排序的核心——Comparator.comparing()接收一个函数,用来提取排序的"键"(这里就是每个内部列表索引为1的元素),默认是升序排序,刚好匹配你需要的1 < 2 < 3 < 4的顺序。如果需要降序,只需要在后面加.reversed()即可。
  • .collect(Collectors.toList()):把排序后的Stream转换回List集合,得到最终结果。

边界情况兜底(可选)

如果你的业务场景中可能存在内部列表长度不足2的情况,直接调用innerList.get(1)会抛出IndexOutOfBoundsException,可以加个兜底逻辑,比如把短列表默认放在最前面:

.sorted(Comparator.comparing(innerList -> innerList.size() >= 2 ? innerList.get(1) : Integer.MIN_VALUE))

运行结果

运行上面的基础代码,输出正好是你期望的结果:

[2, 1, 6, 3]
[3, 2, 6, 3]
[5, 3, 6, 7]
[5, 4, 4, 3]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:27:44