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

Java如何基于内层List的Sample的date字段对Inventory列表降序排序

业务背景

你已经定义了如下数据结构:

public class Inventory {
    private String name;
    private List<Sample> samples;
    // 实际使用前请为所有属性添加对应的getter方法
    public List<Sample> getSamples() {
        return samples;
    }
}

public class Sample {
    private int count;
    private String date;
    public String getDate() {
        return date;
    }
}

List<Inventory> inventories;

同时你已经提前完成了每个Inventory内部samples列表的按date排序,现在需要对外层的inventories列表,依据每个Inventory内Sample的date字段做降序排序。

实现方案

因为内部samples已经完成排序,直接取每个Inventory的samples中你需要作为排序基准的元素的date作为排序键即可,以下是Java 8+的实现代码:

情况1:samples按date升序排序,取最早日期(samples第一个元素)为基准降序

这里加入了空安全处理,如果samples为空可以自定义默认值调整排序优先级:

inventories.sort(Comparator.comparing(
    inv -> inv.getSamples().isEmpty() ? "9999-12-31" : inv.getSamples().get(0).getDate(),
    Comparator.reverseOrder()
));

情况2:samples按date升序排序,取最晚日期(samples最后一个元素)为基准降序

inventories.sort(Comparator.comparing(
    inv -> inv.getSamples().isEmpty() ? "1970-01-01" : inv.getSamples().get(inv.getSamples().size() - 1).getDate(),
    Comparator.reverseOrder()
));

日期格式兼容说明

以上代码默认你的date为yyyy-MM-dd格式,字符串字典序和时间序一致,可直接比较。如果是其他日期格式,建议转成LocalDate再比较避免出错:

inventories.sort(Comparator.comparing(
    inv -> inv.getSamples().isEmpty() ? LocalDate.MIN : LocalDate.parse(inv.getSamples().get(0).getDate()),
    Comparator.reverseOrder()
));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:36:03