Reputation: 452
I have the following HashMap (called "trafficInput") with cities. Each city consists of a list of daily timestamps in milliseconds with two more data points each. One city ("paris") is empty:
{"paris":[],"london":[[1485907200000,182184411,41274],[1485993600000,151646118,36697],[1486080000000,48486138,18998],[1486166400000,5405780,5246],[1486252800000,1194440,1370]],"zurich":[[1485907200000,30200160,155827],[1485993600000,26681354,160269]]}
I want to iterate through this HashMap and add any daily timestamps (with 0 as the two other data points) since February 1, 2017 up until today if they are not yet included in the list. So the optimal output would be:
{"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]]}
I've coded up the following:
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;
}
Unfortunately, the code simply overwrites all existing values, without appending them. What am I missing here?
Upvotes: 0
Views: 118
Reputation: 22233
The put
method does not append, it overwrites. You need to append the values yourself, so instead of doing
ArrayList newCityValuesList = new ArrayList<>(); // create new empty arraylist
newCityValuesList.add(newCityValues);
trafficInput.put(city, newCityValuesList);
You should grab the existing values list and add to them:
ArrayList newCityValuesList = trafficInput.get(city); //get existing values
newCityValuesList.add(newCityValues);
trafficInput.put(city, newCityValuesList);
This way it will still overwrite, but since you grabbed the existing data the result will be the original data + the appended values
Upvotes: 1