Java根据年度将数据分组
现在有这么一组数据
code | name | year |
---|---|---|
45615654 | x1 | 2018-2019 |
78912648 | x2 | 2018-2019 |
42364322 | x3 | 2017-2018 |
87635225 | x4 | 2016-2017 |
我想在Java后台将数据按year分组该怎么做呢
首先数据一定是根据year排序好的
最后返到前台的数据格式是这样的
原理就是year每换一次map就往里put一组year和list
chargeList: [
{
year: 2018-2019,
list: [
{
code: 45615654,
name: "x1"
},
{
code: 78912648,
name: "x2"
},
]
}
]
第一种实现
想要获得这样的数据需要最外层循环根据不重复year的个数来循环
内层再根据year来判断将什么数据放到list中
最后将year和list装在dataMap里
List<ClientResult> clientMsts = clientMstMapper.selectHeatingData2();
List<Map> dataList = new ArrayList<>();
String year = "";
List<String> yearList = new ArrayList<>();
for (ClientResult c : clientMsts) {
if (!year.equals(c.getYear())) {
year = c.getYear();
yearList.add(year);
}
}
for (int i = 0; i < yearList.size(); i++) {
Map<String, Object> map = new HashMap<>();//装的是code和name
Map<String, Object> dataMap = new HashMap<>();//装year和list
List<Map> list = new ArrayList<>();
year = yearList.get(i);
for (ClientResult c : clientMsts) {
if (year.equals(c.getYear())) {
map.put("code", c.getCode());
map.put("name", c.getName());
list.add(map);
}
}
dataMap.put("year", year);
dataMap.put("list", list);
dataList.add(dataMap);
}
Map<String, Object> map = new HashMap<>();
map.put("dataList", dataList);
第二种实现
当year不相同的时候往dataMap中put一组数据
List<ClientResult> clientMsts = clientMstMapper.selectHeatingData2();
List<Map> dataList = new ArrayList<>();
String year = "";
List<Map> lists = null;
for (ClientResult c : clientMsts) {
Map<String, Object> dataMap= new HashMap<>();
boolean a = false;
if (!year.equals(c.getClientPaymentYear())) {
year = c.getClientPaymentYear();
dataMap.put("year", year);
lists = new ArrayList<>();
a = true;
}
Map map = new HashMap();
map.put("code", c.getClientMstCode());
map.put("name", c.getHousingEstateName());
lists.add(map);
if (a) {
dataMap.put("data", lists);
dataList.add(map);
}
}
Map<String, Object> map = new HashMap<>();
map.put("dataList", dataList);
这就是Java后台根据年度分组的详细过程,可能还有别的更好地办法,欢迎一起讨论