gpt4 book ai didi

java - 如何在 Java 中将 ArrayList 添加到 Hashmap

转载 作者:行者123 更新时间:2023-12-01 08:55:18 25 4
gpt4 key购买 nike

我有以下包含城市的 HashMap(称为“trafficInput”)。每个城市都包含一个以毫秒为单位的每日时间戳列表,每个时间戳还有两个数据点。有一个城市(“巴黎”)是空的:

{"paris":[],"london":[[1485907200000,182184411,41274],[1485993600000,151646118,36697],[1486080000000,48486138,18998],[1486166400000,5405780,5246],[1486252800000,1194440,1370]],"zurich":[[1485907200000,30200160,155827],[1485993600000,26681354,160269]]}

我想迭代这个 HashMap 并添加自 2017 年 2 月 1 日到今天的任何每日时间戳(其中其他两个数据点为 0)(如果它们尚未包含在列表中)。所以最佳输出是:

{"paris":[[1485907200000,0,0],[1485993600000,0,0],[1486080000000,0,0],[1486166400000,0,0],[1486252800000,0,0]],"london":[[1485907200000,182184411,41274],[1485993600000,151646118,36697],[1486080000000,48486138,18998],[1486166400000,5405780,5246],[1486252800000,1194440,1370]],"zurich":[[1485907200000,30200160,155827],[1485993600000,26681354,160269],[1486080000000,0,0],[1486166400000,0,0],[1486252800000,0,0]]}

我编写了以下代码:

long startTime = 1485907200; // 01 Feb 2017 00:00:00 GMT
long currentTime = (System.currentTimeMillis() / 1000L);
while (startTime < currentTime) {
for (String city : trafficInput.keySet()) {
for (long[] cityAllValues : trafficInput.get(city)) {
long[] newCityValues = {startTime*1000, 0, 0};
ArrayList newCityValuesList = new ArrayList<>();
newCityValuesList.add(newCityValues);
trafficInput.put(city, newCityValuesList);
}
}
startTime = startTime+86400;
}

不幸的是,代码只是覆盖了所有现有值,而不附加它们。我在这里缺少什么?

最佳答案

put 方法不会追加,而是覆盖。您需要自己附加值,所以不要这样做

ArrayList newCityValuesList = new ArrayList<>(); // create new empty arraylist
newCityValuesList.add(newCityValues);
trafficInput.put(city, newCityValuesList);

您应该获取现有值列表并将其添加到其中:

ArrayList newCityValuesList = trafficInput.get(city); //get existing values
newCityValuesList.add(newCityValues);
trafficInput.put(city, newCityValuesList);

这样它仍然会覆盖,但由于您抓取了现有数据,因此结果将是原始数据 + 附加值

关于java - 如何在 Java 中将 ArrayList 添加到 Hashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068587/

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