java中一个集合里面的对象按照里面的一个属性,这个属性是时间,按时间倒叙收集成集合,然后按照时间相同的分组,并且要按照顺序拿出来每一组
时间: 2024-01-24 07:03:53 浏览: 116
java list集合排序按某一属性排序操作
5星 · 资源好评率100%
可以使用Java 8的Stream API来完成这个任务。首先,我们需要按照时间倒序排序集合,然后使用`Collectors.groupingBy()`方法将对象按照时间分组,最后使用`LinkedHashMap`来保持分组后的顺序。
以下是示例代码:
```java
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
List<MyObject> objects = Arrays.asList(
new MyObject("A", LocalDateTime.parse("2021-01-01 10:00:00", formatter)),
new MyObject("B", LocalDateTime.parse("2021-01-02 10:00:00", formatter)),
new MyObject("C", LocalDateTime.parse("2021-01-02 10:00:00", formatter)),
new MyObject("D", LocalDateTime.parse("2021-01-03 10:00:00", formatter)),
new MyObject("E", LocalDateTime.parse("2021-01-03 10:00:00", formatter)),
new MyObject("F", LocalDateTime.parse("2021-01-03 11:00:00", formatter))
);
Map<LocalDateTime, List<MyObject>> groupedObjects = objects.stream()
.sorted((o1, o2) -> o2.getTime().compareTo(o1.getTime()))
.collect(Collectors.groupingBy(MyObject::getTime, LinkedHashMap::new, Collectors.toList()));
groupedObjects.forEach((time, list) -> {
System.out.println("Time: " + time);
list.forEach(System.out::println);
System.out.println();
});
}
}
class MyObject {
private String name;
private LocalDateTime time;
public MyObject(String name, LocalDateTime time) {
this.name = name;
this.time = time;
}
public String getName() {
return name;
}
public LocalDateTime getTime() {
return time;
}
@Override
public String toString() {
return "MyObject{" +
"name='" + name + '\'' +
", time=" + time +
'}';
}
}
```
输出结果:
```
Time: 2021-01-03T11:00
MyObject{name='F', time=2021-01-03T11:00}
Time: 2021-01-03T10:00
MyObject{name='D', time=2021-01-03T10:00}
MyObject{name='E', time=2021-01-03T10:00}
Time: 2021-01-02T10:00
MyObject{name='B', time=2021-01-02T10:00}
MyObject{name='C', time=2021-01-02T10:00}
Time: 2021-01-01T10:00
MyObject{name='A', time=2021-01-01T10:00}
```
阅读全文