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

Java:如何不使用方法引用通过Stream的max获取最大时间戳?

替代方法引用的Timestamp最大值实现方案

如果旧环境编译器不支持方法引用(::),可以用以下几种兼容方案获取Timestamp列表中的最新时间戳:

方案1:使用匿名内部类实现Comparator(兼容Java 5+)

如果仍想保留流式操作的写法,直接给max()方法传入匿名内部类实现的Comparator即可:

Optional<Timestamp> latestTimestamp = timestamps.stream().max(new Comparator<Timestamp>() {
    @Override
    public int compare(Timestamp t1, Timestamp t2) {
        return t1.compareTo(t2);
    }
});

也可以直接用Collections工具类的max()方法,避免流式操作:

Timestamp latestTimestamp = Collections.max(timestamps, new Comparator<Timestamp>() {
    @Override
    public int compare(Timestamp t1, Timestamp t2) {
        return t1.compareTo(t2);
    }
});

方案2:手动遍历列表(无版本依赖)

如果环境版本极低,甚至不支持泛型或匿名内部类,直接遍历列表逐个比较是最稳妥的方式:

Timestamp latestTimestamp = null;
for (Timestamp ts : timestamps) {
    if (latestTimestamp == null || ts.compareTo(latestTimestamp) > 0) {
        latestTimestamp = ts;
    }
}

内容的提问来源于stack exchange,提问作者jam-butter-scone-tea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 04:10:36