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

Java中按内层首元素降序排序ArrayList<ArrayList<Integer>>

对"row,column"格式字符串ArrayList执行按row值降序排序的实现方法

你不需要纠结必须转换结构才能排序,下面提供两种可直接运行的实现方案,都严格遵循「仅按第一个维度值降序」的规则,其中第二种完全匹配你提出的转嵌套ArrayList再排序的思路。

方案1:直接对原字符串列表排序(无额外结构转换,性能更优)

不需要做额外的数据结构转换,自定义比较器时直接拆分字符串取出row值比较即可,代码实现如下:

import java.util.ArrayList;
import java.util.Comparator;

public class DirectSort {
    public static void main(String[] args) {
        ArrayList<String> coordList = new ArrayList<>();
        coordList.add("21,10");
        coordList.add("19,25");
        coordList.add("32,5");

        // 拆分字符串取逗号前的row值,转整数后执行降序排序
        coordList.sort(Comparator.comparingInt(
                (String coordStr) -> Integer.parseInt(coordStr.split(",")[0])
        ).reversed());

        // 打印结果:[32,5, 21,10, 19,25]
        System.out.println(coordList);
    }
}

方案2:转换为嵌套ArrayList结构后排序(匹配你的初始实现思路)

如果后续业务逻辑需要使用拆分后的行列整数值,可以先转换为ArrayList<ArrayList<Integer>>结构再排序,排序时仅取内层列表第一个索引的元素做比较:

import java.util.ArrayList;
import java.util.Comparator;

public class NestedSort {
    public static void main(String[] args) {
        ArrayList<String> rawStrList = new ArrayList<>();
        rawStrList.add("21,10");
        rawStrList.add("19,25");
        rawStrList.add("32,5");

        // 步骤1:字符串列表转嵌套整数列表
        ArrayList<ArrayList<Integer>> nestedCoordList = new ArrayList<>();
        for (String s : rawStrList) {
            String[] rowCol = s.split(",");
            ArrayList<Integer> coordPair = new ArrayList<>();
            coordPair.add(Integer.parseInt(rowCol[0]));
            coordPair.add(Integer.parseInt(rowCol[1]));
            nestedCoordList.add(coordPair);
        }

        // 步骤2:仅按内层列表第一个元素(row值)做降序排序
        nestedCoordList.sort(Comparator.comparingInt(
                (ArrayList<Integer> pair) -> pair.get(0)
        ).reversed());

        // 打印结果:[[32,5], [21,10], [19,25]],和你给出的预期结果完全一致
        System.out.println(nestedCoordList);
    }
}

注意事项:以上代码默认输入的字符串都是符合数字,数字格式的合法数据,如果存在格式异常的脏数据,需要在类型转换前增加格式校验逻辑,避免抛出NumberFormatException。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 07:12:28