java集合list按时间排序降序
时间: 2023-08-12 09:07:21 浏览: 88
按照时间降序排序,可以在Comparator对象的compare()方法中反转比较结果,示例代码如下:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<MyEntity> list = new ArrayList<>();
list.add(new MyEntity("2021-01-01 10:00:00"));
list.add(new MyEntity("2021-01-02 12:00:00"));
list.add(new MyEntity("2021-01-03 08:00:00"));
Collections.sort(list, new Comparator<MyEntity>() {
@Override
public int compare(MyEntity o1, MyEntity o2) {
return o2.getTime().compareTo(o1.getTime()); // 反转比较结果
}
});
for (MyEntity e : list) {
System.out.println(e.getTime());
}
}
}
class MyEntity {
private String time;
public MyEntity(String time) {
this.time = time;
}
public String getTime() {
return time;
}
}
```
输出结果为:
```
2021-01-03 08:00:00
2021-01-02 12:00:00
2021-01-01 10:00:00
```
阅读全文