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

基于对象字段分组并按组内最大值排序ArrayList求助

解决ArrayList分组排序的问题

没问题,我来帮你搞定这个按货币组内最大金额降序排序的需求!咱们一步步来实现:

1. 先定义数据类

首先得有个类来存储货币和对应的金额,方便后续操作:

class CurrencyAmount {
    private String currency;
    private int amount;

    public CurrencyAmount(String currency, int amount) {
        this.currency = currency;
        this.amount = amount;
    }

    public String getCurrency() {
        return currency;
    }

    public int getAmount() {
        return amount;
    }

    @Override
    public String toString() {
        return currency + " " + amount;
    }
}

2. 准备原始数据

把你给出的货币金额数据转换成列表:

List<CurrencyAmount> amounts = new ArrayList<>();
amounts.add(new CurrencyAmount("USD", 100));
amounts.add(new CurrencyAmount("CAD", 75));
amounts.add(new CurrencyAmount("USD", 10));
amounts.add(new CurrencyAmount("EUR", 80));
amounts.add(new CurrencyAmount("USD", 5));

3. 计算每个货币组的最大金额

首先我们需要先统计出每种货币对应的最大金额,这样排序的时候才有依据:

// 分组并计算每组最大金额
Map<String, Integer> maxAmountMap = amounts.stream()
    .collect(Collectors.groupingBy(
        CurrencyAmount::getCurrency,
        Collectors.maxBy(Comparator.comparingInt(CurrencyAmount::getAmount))
    ))
    .entrySet().stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        entry -> entry.getValue().get().getAmount()
    ));

4. 实现自定义排序逻辑

接下来就是核心的排序部分:

  • 首先按照该货币组的最大金额降序排列
  • 同一货币组内,按照自身金额降序排列(符合你预期的输出顺序)

代码实现如下:

Collections.sort(amounts, new Comparator<CurrencyAmount>() {
    @Override
    public int compare(CurrencyAmount o1, CurrencyAmount o2) {
        // 先比较两组的最大金额,降序
        int maxCompare = Integer.compare(maxAmountMap.get(o2.getCurrency()), maxAmountMap.get(o1.getCurrency()));
        if (maxCompare != 0) {
            return maxCompare;
        }
        // 同一组内,按自身金额降序
        return Integer.compare(o2.getAmount(), o1.getAmount());
    }
});

如果喜欢用Lambda表达式简化的话,也可以写成:

amounts.sort((o1, o2) -> {
    int maxCompare = Integer.compare(maxAmountMap.get(o2.getCurrency()), maxAmountMap.get(o1.getCurrency()));
    return maxCompare != 0 ? maxCompare : Integer.compare(o2.getAmount(), o1.getAmount());
});

5. 输出结果

最后打印排序后的列表,就能得到你想要的结果:

for (CurrencyAmount ca : amounts) {
    System.out.println(ca);
}

执行后输出就是:

USD 100
USD 10
USD 5
EUR 80
CAD 75

完全符合你的预期需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:39:08