java - 如何使用哈希图添加增量值
问题描述
我有一个称为 client 的表,其中 ia 列称为 created_time ,所以实际上我想绘制一张地图,以便我可以知道在哪一年和哪一个月添加了多少客户?现在的问题是假设在 2018 年 11 月添加了 2 个客户,在 2018 年 12 月添加了 0 个客户,所以在 12 月我也会显示 2 个(就像上面的月份 + 当前月份),如果在 2019 年 1 月添加了 1 个客户,那么我会展示 3 等等
所以为了解决这个问题,我创建了一个哈希映射,其中第一个键是年,我制作了另一个哈希映射,其中键是月份,然后添加了客户端的编号,例如 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));
}
}
}
解决方案
见下文,如果我正确理解您的问题,它应该可以解决您的问题
- 迭代所有客户端
- 如果年份地图不包含它,则添加
- 否则从 yearmap 获取现有条目
- 添加以迭代计数器为最新值的月图
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 排序
推荐阅读
- masstransit - AutofacRegistrationExtensions.ConfigureConsumers(IComponentContext) 按约定注册接收端点
- android - Flutter 更改右上角的文本位置
- sql - 如何连接具有相同 ID 但日期不同的所有不同行并将其作为具有新列(如 DATE_0、DATE_1、DATE_2...)的唯一行返回?
- path - 如何替换 PathBuf 或 Path 的文件扩展名?
- python - 通过字符串向 tkinter 按钮添加命令
- git - 如何将任何添加/删除的 git 日志显示到子目录的一级但不递归?
- python - 为与 gevent 一起使用的 gunicorn 设置 worker_connections 设置时应该考虑什么?
- angular - 在 Angular Reactive Forms、City/State 或 zip 中验证非此即彼的字段逻辑
- c# - Asp.net core 3 Web Api post请求不起作用
- python - Python:超调目标,需要向量或 PID 调整?