如何给List<Map<String, Object>> resultList = new ArrayList<>();按照里边的时间进行排序
时间: 2023-10-14 14:20:59 浏览: 92
可以使用Java 8的Stream API和Comparator来对List<Map<String, Object>>进行排序,具体步骤如下:
1. 定义一个Comparator,用于比较两个Map<String, Object>对象中的时间字段:
```
Comparator<Map<String, Object>> mapComparator = (map1, map2) -> {
LocalDateTime time1 = LocalDateTime.parse((String) map1.get("time"));
LocalDateTime time2 = LocalDateTime.parse((String) map2.get("time"));
return time1.compareTo(time2);
};
```
其中,假设时间字段的键为"time",可以根据实际情况进行修改。
2. 使用Stream API对List<Map<String, Object>>进行排序:
```
resultList = resultList.stream()
.sorted(mapComparator)
.collect(Collectors.toList());
```
这里使用了sorted方法对List中的元素进行排序,排序的依据是mapComparator。最后使用collect方法将排序后的结果收集到一个新的List中。
完整代码示例:
```
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class SortListMapByTime {
public static void main(String[] args) {
// 构造测试数据
List<Map<String, Object>> resultList = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("id", 1);
map1.put("name", "张三");
map1.put("time", "2021-01-01T10:00:00");
Map<String, Object> map2 = new HashMap<>();
map2.put("id", 2);
map2.put("name", "李四");
map2.put("time", "2021-01-02T12:00:00");
Map<String, Object> map3 = new HashMap<>();
map3.put("id", 3);
map3.put("name", "王五");
map3.put("time", "2021-01-03T08:00:00");
resultList.add(map1);
resultList.add(map2);
resultList.add(map3);
// 定义Comparator
Comparator<Map<String, Object>> mapComparator = (map1, map2) -> {
LocalDateTime time1 = LocalDateTime.parse((String) map1.get("time"));
LocalDateTime time2 = LocalDateTime.parse((String) map2.get("time"));
return time1.compareTo(time2);
};
// 排序
resultList = resultList.stream()
.sorted(mapComparator)
.collect(Collectors.toList());
// 输出结果
for (Map<String, Object> map : resultList) {
System.out.println(map);
}
}
}
```
输出结果:
```
{id=1, name=张三, time=2021-01-01T10:00:00}
{id=2, name=李四, time=2021-01-02T12:00:00}
{id=3, name=王五, time=2021-01-03T08:00:00}
```
阅读全文