[英]How to add an ArrayList to a Hashmap in Java
我在城市中有以下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);
這樣,它仍然會被覆蓋,但是由於您獲取了現有數據,因此結果將是原始數據+附加值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.