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

如何将字符串按内嵌的金额数值排序后存入ArrayList

基于字符串内含金额排序存入ArrayList的实现方案

实现逻辑

  • 金额提取:示例字符串中金额为按空格分割后的第二个字段,分割时用\\s+匹配连续多空格,避免字段提取错位
  • 金额比较优先使用BigDecimal类型,避免使用double/float带来的精度丢失问题,保证金额排序的准确性
  • 调用集合排序方法传入自定义比较器完成排序

代码实现

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SortByAmount {
    public static void main(String[] args) {
        String s1="TO210727B3 1541.81 BBN892400                         S103";
        String s2="TI210727T6 500.55 BBN793700                TDOMCATTTS205";

        ArrayList<String> resultList = new ArrayList<>();
        resultList.add(s1);
        resultList.add(s2);

        // 自定义比较器实现按金额升序排序
        Collections.sort(resultList, new Comparator<String>() {
            // 匹配金额的正则,适配两位小数的金额格式
            private final Pattern AMOUNT_PATTERN = Pattern.compile("\\d+\\.\\d{2}");
            @Override
            public int compare(String str1, String str2) {
                // 方式1:按空格分割提取第二个字段作为金额(适配示例字符串结构)
                // BigDecimal amount1 = new BigDecimal(str1.trim().split("\\s+")[1]);
                // BigDecimal amount2 = new BigDecimal(str2.trim().split("\\s+")[1]);

                // 方式2:正则提取金额,适配金额位置不固定的场景
                BigDecimal amount1 = extractAmount(str1, AMOUNT_PATTERN);
                BigDecimal amount2 = extractAmount(str2, AMOUNT_PATTERN);
                return amount1.compareTo(amount2);
            }

            private BigDecimal extractAmount(String str, Pattern pattern) {
                Matcher matcher = pattern.matcher(str);
                if (matcher.find()) {
                    return new BigDecimal(matcher.group());
                }
                // 未匹配到金额时可根据业务需求返回默认值或抛出异常
                return BigDecimal.ZERO;
            }
        });

        // 输出结果和示例要求一致
        System.out.println("Output ArrayList l=" + resultList);
    }
}

运行输出

Output ArrayList l=[TI210727T6 500.55 BBN793700                TDOMCATTTS205, TO210727B3 1541.81 BBN892400                         S103]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:39:05