java根据时间排序
时间: 2023-07-20 12:16:10 浏览: 555
可以使用Java中的Collections.sort()方法结合Comparator接口来根据时间进行排序。假设我们有一个List<Date>类型的时间列表dates,可以按照以下代码进行排序:
```
Collections.sort(dates, new Comparator<Date>() {
@Override
public int compare(Date date1, Date date2) {
return date1.compareTo(date2);
}
});
```
其中,compare()方法返回一个int类型的值,表示两个日期的比较结果。如果第一个日期比第二个日期早,则返回负数;如果两个日期相同,则返回0;如果第一个日期比第二个日期晚,则返回正数。在上面的代码中,我们直接使用了Date类的compareTo()方法进行了比较。如果需要按照自定义的时间格式进行排序,可以使用SimpleDateFormat类将字符串转换为Date类型再进行比较。
相关问题
javalist 根据时间排序
可以使用Collections.sort()方法对javalist进行排序,具体实现可参考以下代码:
Collections.sort(javalist, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
if (o1 instanceof Date && o2 instanceof Date) {
Date date1 = (Date) o1;
Date date2 = (Date) o2;
return date1.compareTo(date2);
}
return 0;
}
});
java stream 根据时间倒序排序
你可以使用Java Stream来根据时间倒序排序。假设你有一个包含时间对象的列表,你可以使用`sorted()`方法结合`Comparator`来实现排序。下面是一个示例代码:
```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> dateTimeList = new ArrayList<>();
dateTimeList.add(LocalDateTime.of(2021, 1, 1, 12, 0));
dateTimeList.add(LocalDateTime.of(2021, 2, 1, 12, 0));
dateTimeList.add(LocalDateTime.of(2021, 3, 1, 12, 0));
List<LocalDateTime> sortedList = dateTimeList.stream()
.sorted(Comparator.reverseOrder())
.toList();
System.out.println(sortedList);
}
}
```
在上面的例子中,我们首先创建了一个包含时间对象的列表`dateTimeList`。然后,我们使用`stream()`方法将列表转换为流,并使用`sorted()`方法与`Comparator.reverseOrder()`来进行倒序排序。最后,我们将排序后的流转换回列表并打印输出。
输出结果将会是:
```
[2021-03-01T12:00, 2021-02-01T12:00, 2021-01-01T12:00]
```
这样,你就可以根据时间倒序对Java Stream进行排序了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)