使用Stream流实现以List<Map<String, Object>>集合中Map的key值进行排序
创建一个list存入数据
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Map<String, Object> map = new HashMap<>();
map.put("id", i);
map.put("name", "张三" + i);
list.add(map);
}
用id来作比较:
//升序排列
list = list.stream().sorted((map1, map2) -> {
return Integer.valueOf(map1.get("id").toString()).compareTo(Integer.valueOf(map2.get("id").toString()));
}).collect(Collectors.toList());
降序排列仅是返回时交换map1,2前后位置
//降序排列
list = list.stream().sorted((map1, map2) -> {
return Integer.valueOf(map2.get("id").toString()).compareTo(Integer.valueOf(map1.get("id").toString()));
}).collect(Collectors.toList());
由于map的value值类型是Object,所有要注意在使用比较器的时候如果以整数类型作比较的话需要转成Integer类型。
List<Map<String, Object>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Map<String, Object> map = new HashMap<>();
map.put("id", i);
map.put("name", "张三" + i);
list.add(map);
}
for (int i = 11; i < 20; i++) {
Map<String, Object> map = new HashMap<>();
map.put("id", i);
map.put("name", "张三" + i);
list.add(map);
}
list = list.stream().sorted((map1, map2) -> {
return map1.get("id").toString().compareTo(map2.get("id").toString());
}).collect(Collectors.toList());
list.forEach(map -> {
System.out.println(map.toString());
});
标签:Map,Stream,map,List,list,map1,toString,id
From: https://www.cnblogs.com/ComfortableM/p/17044225.html