list集合中的map集合通过map的creattime键值进行时间排序,map不止有creattime键值
时间: 2024-01-20 16:02:56 浏览: 116
Java中对list map根据map某个key值进行排序的方法
,也可以根据其他键值进行排序,以下是根据creattime进行排序的示例代码:
```
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("name", "Alice");
map1.put("age", 20);
map1.put("creattime", new Date(2021, 0, 1));
list.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "Bob");
map2.put("age", 25);
map2.put("creattime", new Date(2021, 3, 1));
list.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("name", "Charlie");
map3.put("age", 30);
map3.put("creattime", new Date(2021, 2, 1));
list.add(map3);
// 按照creattime排序
Collections.sort(list, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
Date d1 = (Date) o1.get("creattime");
Date d2 = (Date) o2.get("creattime");
return d1.compareTo(d2);
}
});
// 输出排序结果
for (Map<String, Object> map : list) {
System.out.println(map);
}
}
}
```
输出结果:
```
{name=Alice, age=20, creattime=Sat Jan 01 00:00:00 CST 3921}
{name=Charlie, age=30, creattime=Mon Mar 01 00:00:00 CST 3921}
{name=Bob, age=25, creattime=Mon Apr 01 00:00:00 CST 3921}
```
阅读全文