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

如何按字符串最后一个点后的整数值对List<String>进行排序?

解决方案

要实现按SKU最后一个点后的整数值排序,你需要自定义Comparator替代默认的字符串排序逻辑,具体代码如下:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SkuSortExample {
    public static void main(String[] args) {
        List<String> skuList = new ArrayList<>();
        skuList.add("com.replaysport.pickempartyapp.20");
        skuList.add("com.replaysport.pickempartyapp.12");
        skuList.add("com.replaysport.pickempartyapp.75");
        skuList.add("com.replaysport.pickempartyapp.30");
        skuList.add("com.replaysport.pickempartyapp.5");
        skuList.add("com.replaysport.pickempartyapp.100");
        skuList.add("com.replaysport.pickempartyapp.50");

        // 自定义Comparator,按最后一个点后的数字排序
        Collections.sort(skuList, new Comparator<String>() {
            @Override
            public int compare(String sku1, String sku2) {
                // 提取最后一个点后的数字部分
                Integer num1 = Integer.parseInt(sku1.substring(sku1.lastIndexOf(".") + 1));
                Integer num2 = Integer.parseInt(sku2.substring(sku2.lastIndexOf(".") + 1));
                // 按整数从小到大排序
                return num1.compareTo(num2);
            }
        });

        // 输出验证排序结果
        for (String sku : skuList) {
            System.out.println(sku);
        }
    }
}

代码说明

  • sku.lastIndexOf(".") + 1:定位到最后一个点的下一个字符,截取后面的数字字符串
  • Integer.parseInt():将截取到的字符串转为整数,规避字符串排序的逻辑问题(比如"100"和"5"的字符串比较偏差)
  • num1.compareTo(num2):实现整数升序排序,若需要降序则返回num2.compareTo(num1)

异常处理(可选)

如果SKU列表中存在格式不符合预期的字符串(比如无点、点后非数字),可在compare方法中添加异常捕获,避免程序崩溃:

@Override
public int compare(String sku1, String sku2) {
    try {
        Integer num1 = Integer.parseInt(sku1.substring(sku1.lastIndexOf(".") + 1));
        Integer num2 = Integer.parseInt(sku2.substring(sku2.lastIndexOf(".") + 1));
        return num1.compareTo(num2);
    } catch (IndexOutOfBoundsException | NumberFormatException e) {
        // 处理格式错误的SKU,比如将其放到末尾或按原字符串排序
        return sku1.compareTo(sku2);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:06:26