Comparator.comparing 比较时间
时间: 2023-11-07 09:55:20 浏览: 269
Comparator.comparing 方法可以用于比较时间。在 Java 中,可以使用 Comparator.comparing 方法来创建一个比较器,然后在排序时使用该比较器来比较时间。
下面是一个示例代码,演示了如何使用 Comparator.comparing 方法比较时间:
```java
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<LocalDateTime> times = new ArrayList<>();
times.add(LocalDateTime.of(2021, 1, 1, 9, 0, 0));
times.add(LocalDateTime.of(2021, 1, 1, 10, 0, 0));
times.add(LocalDateTime.of(2021, 1, 1, 8, 0, 0));
// 使用 Comparator.comparing 方法比较时间
Comparator<LocalDateTime> comparator = Comparator.comparing(time -> time);
// 按时间排序
times.sort(comparator);
// 输出排序结果
for (LocalDateTime time : times) {
System.out.println(time);
}
}
}
```
这段代码创建了一个包含三个时间的列表 `times`,然后使用 Comparator.comparing 方法创建了一个比较器 `comparator`,该比较器将按照时间的自然顺序进行比较。最后,通过调用 `times.sort(comparator)` 方法对时间进行排序,并输出排序结果。
阅读全文
相关推荐













