Reputation: 2455
I have one set whose keys are String and List of type String I want to make a HashMap out of this Set and List. The set contains categories and the list contains places belonging to those categories. Following is what I tried
Set<Entry<String, Integer>> setUserPreferences = sortedUserPreferences.entrySet();
Map<String , Integer> sortedPlaces = new HashMap<String, Integer>();
List<String> topPlaces = new ArrayList<String>();
Map<String , List<String>> finalPlaces = new HashMap<String, List<String>>();
for (Entry<String, Integer> entry : setUserPreferences) {
sortedPlaces = placesService.sortPlaces(categorisedPlaces.get(entry.getKey()));
int counter = 0;
for (Map.Entry<String, Integer> sortedplace : sortedPlaces.entrySet()) {
topPlaces.add(sortedplace.getKey());
counter++;
if(counter == 5){
sortedPlaces.clear();
break;
}
}
finalPlaces.put(entry.getKey(), topPlaces);
topPlaces.clear();
}
First I iterate over the set and for each key I get the sorted Places, out of the sorted places I pick the top 5 places for each category, Finally I put it in the map where the key is the category and value is the list of top 5 places in that category.
I need to clear the topPlaces list for each iteration over the set because I dont want to have the places from one category appear in the other, but once I put the list in map(finalPlaces) and clear the list it also clear the map values.
How can I clear the list without clearing the map values.
Thanks
Upvotes: 1
Views: 106
Reputation: 2361
topPlaces
is a reference to an Object, not a primitive. So, if you store it in the map, you have two references to the same Object, one inside the Map and one outside. If you wipe one, you wipe both.
If you want to clear topPlaces
without deleting the stored list, you need to copy it before adding it to the Map.
Something like this:
finalPlaces.put(entry.getKey(), new ArrayList<String(topPlaces));
Upvotes: 2