我有ObjectLocation的列表,声明为

List<ObjectLocation> myLocations;


这是ObjectLocation的样子:

public class ObjectLocation {
    int locationID, ratingCount = 0;
}


好的,现在myLocations拥有数千个locationID。如果我有特定的locationID,如何在myLocations的内容中搜索locationID,并获取搜索到的locationID的索引(在myLocations内)及其ratingCount?

最佳答案

对于这种查找,我将切换为使用Map<Integer, ObjectLocation>并将条目存储在地图中,如下所示:

Map<Integer, List<ObjectLocation>> myLocationMap = new HashMap<>();
List<ObjectLocation> currentList = myLocationMap.get(oneLocation.locationID);
if(currentList == null) {
    // We haven't stored anything at this locationID yet,
    // so create a new List and add it to the Map under
    // this locationID value.
    currentList = new ArrayList<>();
    myLocationMap.put(oneLocation.locationID, currentList);
}
currentList.add(oneLocation);


现在,您可以像这样从地图上抓取所有具有特定值的ObjectLocation条目,从而快速获取它们:

List<ObjectLocation> listOfLocations = myLocationMap.get(someLocationId);


假设多个locationID实例可以具有相同的ObjectLocation值。如果不是,那么地图中就不需要locationID,只需一个List<ObjectLocation>

07-24 09:32