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
相关产品推荐
相关产品推荐

