Search code examples
javajdbchashmapresultset

Map object keeps getting overwritten when adding


I have a database call that will return a result set with city and states into a result set object called cityAndState. I am trying to loop through and put each city and state into a map and then add to an array list of maps.
So I have an array list with 50 city and state Maps with <key,values> of city and state. For instance [{city-Los Angeles, state=California},...] But each time I am overwriting the value.

Map<String,String> citiesAndStateCombinations = new HashMap<>();

List<Map<String,String> citiesStates = new ArrayList<>();

while(cityAndState.next()){
citiesStates.put("city", cityAndState.getString("city");
citiesStates.put("state", cityAndState.getString("state");
citiesAndStateCombinations.add(citiesStates); 
}

Leaves an array with the last values printed 50 times. [{city-Boise, state=Idaho}, {city=Boise, state=Idaho}.....50}

Each time it erases the previous value. I see why it is doing it, it's setting all the elements to the last value added which makes sense but is there a way to add the values so I am left with an array of the 50 cities and States?


Solution

  • The thing is you're implementing HashMap in the wrong way, or you misunderstood it: "A Map cannot contain duplicate keys and each key can map to at most one value." What you're doing in the above code -

    citiesStates.put("city", cityAndState.getString("city");
    citiesStates.put("state", cityAndState.getString("state");
    

    You're putting values with the same key "city" & "state" that's why it's overwriting the values.

    The correct way to do this will be -

    Map<String,String> citiesAndStateCombinations = new HashMap<>();
    
    while(cityAndState.next()){
    if(!citiesAndStateCombinations.containskey(cityAndState.getString("city"))){
       citiesAndStateCombinations.put(cityAndState.getString("city"), cityAndState.getString("state"))
    }
    }
    

    This will give you a city and state unique map now if you want it to be added to a list you can add this line at last but I don't see any use of it -

    List<Map<String,String> citiesStates = new ArrayList<>();
    citiesStates.add(citiesAndStateCombinations);
    

    Please add this after closing the while loop.

    ----------EDITED----------

    To achieve the solution which you're looking for you need to write something like this -

    enter code here
    while(----){
    Map<String,String> citiesAndStateCombinations = new HashMap<>();
    if(citiesAndStateCombinations.containsKey("city="+cityAndState.getString("city"))){
        citiesAndStateCombinations.put(cityAndState.getString("city"), cityAndState.getString("state"))
        citiesStates.add(citiesAndStateCombinations);
    }
    

    This will give you desired output -

    [{city=XXXXXX=state=XXXXXX}, 
    {city=XXXXXX=state=XXXXXX}, 
    {city=XXXXXX=state=XXXXXX}]