Is there anyway to have a map defined as Map<String, String> that can be added to an array list defined as List<Map<String, String> that has the same key? Ideally we would have an arraylist of maps
[{firstName=john}, {firstName=Kelly}, {firstName=Jack}]
The reason I need the same key is for react.js ui I will need to map over these items and I need to have the same key in each object so I can call
List.map(key, index) = > key.firstName
To build the ui component. Is this possible?
Map<String,String> names = new HashMap<>();
List<Map<String,String> firstNamesLastNamesList = new ArrayList<>();
while(resultSet.next()){
names.put("firstName", resultSet.getString("firstName");
names.put("lastName", resultSet.getString("lastName");
firstNamesLastNamesList.add(names);
}
The values to populate each map will come from a database. Currently when I add each object to the List of maps as you might imagine, the previous map is overwritten due to the same key of firstName. I am left with a List like [{firstName=Jack, lastName=Hammer}, {firstName=Jack, lastName=Hammer}, {firstName=Jack, lastName=Hammer}] not [{firstName=John, lastName=Carpenter}, {firstName=Kelly, lastName=Johnson}, {firstName=Jack, lastName=Black}] which is the desired out put. Any help would be greatly appreciated.
CodePudding user response:
Your code is doing what is expected. the object that you are creating is before the loop
Map<String,String> names = new HashMap<>();
when you create this object you are saying make a new object called names at memory address 0x84927 - some random address.
then you are adding a reference to that object at index i for each item in the list. when you change the object names the list will look for memory address 0x84927 for each index in the firstNamesLastNamesList.
you need to put that piece of code in the while loop
CodePudding user response:
You can update your code like this:
Here,
You need to create a new Map for each resultSet inside the loop and then add it to the list. (And as you are creating map outside the loop which is creating a problem.)
List<Map<String,String>> firstNamesLastNamesList = new ArrayList<>();
while(resultSet.next()){
Map<String,String> names = new HashMap<>();
names.put("firstName", resultSet.getString("firstName"));
names.put("lastName", resultSet.getString("lastName"));
firstNamesLastNamesList.add(names);
}