在工作中,可能会遇到查询出的数据不符合前端要求,进行组装数据
List<Map<String, Object>> mapList = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("time", "2022-11-1 10:23:30");
map.put("name", "李四");
map.put("age", "18");
mapList.add(map);
Map<String, Object> map1 = new HashMap<>();
map1.put("time", "2022-11-1 11:34:12");
map1.put("name", "王五");
map1.put("age", "20");
mapList.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("time", "2022-11-2 12:12:12");
map2.put("name", "张三");
map2.put("age", "25");
mapList.add(map2);
假如查询出的数据是这种格式,我们需要根据每一天的数据生成新的集合,组装数据集格式是下图这样的
按照以前的方法可能需要循环遍历,判断进行组装新的数据,代码即臃肿又难看,现在的lambda表达式加stream流,进行组合就会特别快,而且代码美观,可读性强
Map<Object, List<Map<String, Object>>> list = mapList.stream()
.peek(item -> {
String time = item.get("time").toString();
Date date1 = DateUtil.parse(time);
String hour = DateUtil.formatTime(date1);
item.put("hour", hour);
})
.collect(Collectors.groupingBy(item -> {
String time = item.get("time").toString();
Date date1 = DateUtil.parseDate(time);
return DateUtil.formatDate(date1);
}));
System.out.println(list);
通过collect.groupingBy进行分组,就可以获得到每一天时间为key的map数据,再进行数据转化为集合List或JSON数组都可以
List<Map<String, Object>> mm = list.entrySet().stream()
.map(item -> {
Map<String, Object> map3 = new HashMap<>();
map3.put("ymd", item.getKey());
map3.put("list", item.getValue());
return map3;
}).collect(Collectors.toList());
System.out.println(new JSONArray(mm));
就这么简单的两段代码就可以组装成前端复杂的数据结构集。
不得不说,java的新特性用起来是真的强大,让人写起代码来心情愉悦。看着也开心