gpt4 book ai didi

java - 如何使用 的 HashMap 添加增量值

转载 作者:行者123 更新时间:2023-12-02 09:21:35 29 4
gpt4 key购买 nike

我有一个称为 client 的表,其中有一列称为created_time ,所以实际上我想绘制一个 map ,以便我可以知道在哪一年和哪一个月添加了多少客户?现在的要求是假设在 2018 年 11 月添加了 2 个客户,在 2018 年 12 月添加了 0 个客户,所以在 12 月我也会显示 2 个客户(就像上面的月份 + 当前月份),如果在 2019 年 1 月添加了 1 个客户,那么我将显示 3 等等

为了解决这个问题,我创建了一个 hashMap,其中第一个键是年份,我创建了另一个 hashMap,其中键是月份,然后添加了客户端的编号,例如 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));
}
}
}

最佳答案

请参阅下文,如果我正确理解您的问题,它应该可以解决您的问题

  1. 迭代所有客户端
  2. 如果年份 map 不包含则添加
  3. 否则从年图中获取现有条目
  4. 添加月份图,并将迭代计数器作为最新值
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 排序

关于java - 如何使用 <Integer,HashMap<Integer,Integer> 的 HashMap 添加增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58660398/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com