我有一个称为client的表,其中有一列称为created_time,所以实际上我想绘制一个地图,以便可以确定在哪一年和哪个月中添加了多少客户?现在要问的是假设在2018年11月添加了2个客户端,在2018年12月添加了0个客户端,因此在12月我也将显示2个(类似于上述月份+本月),如果在2019年1月添加了1个客户端,则我将显示3,依此类推
为了解决这个问题,我创建了一个hashMap,其中第一个键是year,我制作了另一个hashMap,其中键是month,然后添加了客户编号,例如HashMap>预期输出::
clientsByMonth": {
"2018": {
"10": 1,(1 client added in oct)
11,1( as 0 client added in nov)
12,2( as 1 client added in december)
},
"2019": {
"1": 2, ( as no client added )
"2": 4, (as 2 client added)
"3": 5,
"4": 5
}
HashMap<Integer, HashMap<Integer, Integer>> clientsByYear = new HashMap<>();
List<Client> clientList = clientRepository.findAll();
for (int i = 0; i < clientList.size(); i++) {
Instant instant = Instant.ofEpochMilli(clientList.get(i).getCreatedTime().getTime());
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
Integer month = localDateTime.toLocalDate().getMonth().getValue();
Integer year = localDateTime.toLocalDate().getYear();
if (!clientsByYear.containsKey(year)) {
HashMap<Integer, Integer> clientByMonth = new HashMap<>();
clientByMonth.put(month, 1);
clientsByYear.put(year, clientByMonth);
} else {
HashMap<Integer, Integer> clientByMonth = clientsByYear.get(year);
if (!clientByMonth.containsKey(month)) {
int clients = 0;
for (int j = month - 1; j >= 0; j--) {
if (clientByMonth.containsKey(j)) {
clients = clients + clientByMonth.get(j);
break;
}
}
clientByMonth.put(month, (clients + 1));
} else if (clientByMonth.containsKey(month)) {
int clients = clientByMonth.get(month);
clientByMonth.put(month, (clients + 1));
}
}
}
答案 0 :(得分:1)
请参阅下文,如果我正确理解您的问题,它将可以解决您的问题
for (int i = 1; i <=clientList.size() ; i++) {
...
if (!clientsByYear.containsKey(year)) {
HashMap<Integer, Integer> clientByMonth = new HashMap<>();
clientByMonth.put(month, i);
clientsByYear.put(year, clientByMonth);
} else {
HashMap<Integer, Integer> clientByMonth = clientsByYear.get(year);
clientByMonth.put(month, i);
}
}
System.out.println(clientsByYear);
}
期望:输入数据基于时间asc排序