简体   繁体   English

如何从 Java 中的数组获取最小 LocalDateTime

[英]How to get minimum LocalDateTime from array in Java

I have an array:我有一个数组:

LocalDateTime[] onTimes

I would like to find an efficient way (without iteration) of finding the minimum LocalDateTime.我想找到一种找到最小 LocalDateTime 的有效方法(无需迭代)。

Is there a quick way to do this?有没有快速的方法来做到这一点?

You could, conceivably, use recursion;可以想象,你可以使用递归; but I would not recommend that for performance.但我不建议这样做以提高性能。 The best way I can think of is using the streams api like我能想到的最好的方法是使用流 api 之类的

LocalDateTime min = Arrays.stream(onTimes).min(Comparator.naturalOrder())
        .orElseThrow();

Note: This still iterates all elements internally to find the minimum.注意:这仍然在内部迭代所有元素以找到最小值。

For completeness sake;为了完整起见; to do this without iteration, as I said, might be done recursively.如我所说,在没有迭代的情况下执行此操作可能会递归完成。

public static LocalDateTime getMinimum(LocalDateTime[] onTimes) {
    return getMinimum(onTimes, 0);
}

private static LocalDateTime getMinimum(LocalDateTime[] onTimes, int i) {
    if (i + 1 < onTimes.length) {
        return min(onTimes[i], getMinimum(onTimes, i + 1));
    } else {
        return onTimes[i];
    }
}

private static LocalDateTime min(LocalDateTime a, LocalDateTime b) {
    if (a.compareTo(b) <= 0) {
        return a;
    }
    return b;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "如何从 Java 8 中的 LocalDateTime 获取毫秒数" - How to get milliseconds from LocalDateTime in Java 8 Java - 从 Double 获取 LocalDateTime - Java - Get LocalDateTime from Double 如何在 Java 8 上使用 LocalDateTime.now() 获取当前的 LocalDateTime 包括秒数 - How to get the current LocalDateTime including seconds with LocalDateTime.now() on Java 8 如何将 localdatetime 作为值数组放入 java - How to put localdatetime as array of values in java 如何在返回类型为 LocalDateTime 的方法中从 LocalDateTime 对象中获取第二个? - How to get the second from LocalDateTime objects in a method with return type LocalDateTime? 如何获得二维数组中的最小值 - how to get minimum in 2d array java 如何使用LocalDateTime java检查最小和最大时间,即最小10:00和最大时间10:30 - How to check minimum and max times with LocalDateTime java ie minimum 10:00 and max time 10:30 如何从TemporalAccessor获取ZoneId,LocalDateTime和Instant - How to get ZoneId, LocalDateTime and Instant from TemporalAccessor Java 由 object 列表组成的组包含 2 个 LocalDateTime 字段,然后从中获取最大值和最小值 - Java group by a list of object contain 2 LocalDateTime field, then get the maximum and also minimum value out of it 如何将 JSON LocalDateTime 解析为 Java LocalDateTime? - How to parse JSON LocalDateTime to Java LocalDateTime?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM