java将集合和列表合并到HashMap
我有一个集合,它的键是String和List类型的String,我想用这个集合和List做一个HashMap。集合包含类别,列表包含属于这些类别的位置。以下是我尝试过的
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();
}
首先,我在集合中迭代,对于每个关键点,我得到排序的位置,从排序的位置中,我为每个类别选择前5位,最后我把它放在地图中,关键点是类别,值是该类别中前5位的列表
我需要清除集合中每个迭代的topPlaces列表,因为我不想让一个类别中的位置出现在另一个类别中,但一旦我将列表放入map(finalPlaces)并清除列表,它也会清除地图值
如何在不清除映射值的情况下清除列表
谢谢
# 1 楼答案
topPlaces
是对对象的引用,而不是原语。所以,如果你把它存储在地图上,你对同一个对象有两个引用,一个在地图内,一个在地图外。如果你擦一个,你就擦两个如果要清除
topPlaces
而不删除存储的列表,则需要在将其添加到地图之前复制它比如: