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

Java中按字典序排序List<List<Integer>>结果不符合预期如何解决

问题根因

你编写的比较器逻辑违反了字典序逐位比较的规则,同时不符合Comparator的接口约定,最终导致排序结果异常:

  • 字典序要求只有前一位元素相等时,才需要比较下一位元素,但你的判断逻辑是只要item1的任意一位大于item2对应位,就判定item1更大,完全忽略了前序位的优先级。比如比较[1,2,84,92]和[1,3,76,99]时,第二位2<3本就可以判定前者更小,但你的逻辑会因为前者第三位84>76错误判定前者更大。
  • 你的比较器永远只返回1或-1,没有处理两个元素相等时返回0的情况,违反了Comparator的对称约定,会导致排序逻辑混乱。
正确实现方案

方案1:手动逐位比较(兼容性好)

java.util.Collections.sort(result, (item1, item2) -> {
    // 按索引顺序逐位比较
    for (int i = 0; i < item1.size(); i++) {
        int cmp = item1.get(i).compareTo(item2.get(i));
        if (cmp != 0) {
            // 前一位不相等直接返回比较结果
            return cmp;
        }
    }
    // 所有位相等返回0
    return 0;
});

方案2:链式比较器(Java 8+ 写法更简洁)

如果你的子列表长度固定为4,可直接用Comparator的链式API实现,可读性更高:

result.sort(Comparator.comparingInt((List<Integer> l) -> l.get(0))
    .thenComparingInt(l -> l.get(1))
    .thenComparingInt(l -> l.get(2))
    .thenComparingInt(l -> l.get(3)));

两种实现都能得到你预期的输出:[[1, 1, 76, 99], [1, 2, 84, 92], [1, 3, 76, 99]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:36:05