首页 > 解决方案 > 如何使用哈希图添加增量值

问题描述

我有一个称为 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));
            }
        }
    }

标签: javaspring-bootspring-data-jpahashmap

解决方案


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

  1. 迭代所有客户端
  2. 如果年份地图不包含它,则添加
  3. 否则从 yearmap 获取现有条目
  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 排序


推荐阅读