我有一个集合,其键是字符串和字符串类型的列表,我想用这个集合和列表创建一个 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 个地点,最后我将其放入 map 中,其中键是类别,值为该类别中前 5 名的列表。
我需要清除集合上每次迭代的 topPlaces 列表,因为我不想让一个类别中的地点出现在另一类别中,但是一旦我将列表放入 map(finalPlaces) 并清除列表,它也会清除 map 值。
如何在不清除 map 值的情况下清除列表。
谢谢
最佳答案
topPlaces
是对对象的引用,而不是基元。因此,如果将其存储在 map 中,则会有对同一对象的两个引用,一个在 map 内部,一个在 map 外部。如果您删除其中一个,则同时删除两个。
如果您想清除topPlaces
而不删除存储的列表,则需要在将其添加到 map 之前复制它。
类似这样的事情:
finalPlaces.put(entry.getKey(), new ArrayList<String(topPlaces));
关于java - 将集合和列表合并到 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23013685/