按属性搜索自定义对象列表

时间:2015-05-17 14:48:50

标签: java

我有ObjectLocation列表,声明为

List<ObjectLocation> myLocations;

这就是ObjectLocation的样子:

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

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

5 个答案:

答案 0 :(得分:2)

好吧,你循环遍历列表中的所有元素,如果locationID匹配,你就找到了你的元素!

int idx=0;
for (ObjectLocation ol:myLocations){
  if (ol.locationID==searchedLocationID){
    // found at index idx!!  
  }
  idx++;
}

更高效的是,你可以拥有一个Map<Integer,ObjectLocation>,其中键是ObjectLocation的locationID,以便更快地查找。

答案 1 :(得分:1)

对于这种查找,我会切换到使用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特定值的所有locationID条目,方法是从地图中抓取它们,如下所示:

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

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

答案 2 :(得分:0)

为了便于搜索和查找ObjectLocation个对象,您应首先在.equals(Object o)类中定义允许将ObjectLocationObjectLocation进行比较的.indexOf(Object o)'方法另一个。之后,您所要做的就是使用ObjectLocation来获取您要查找的public class ObjectLocation { int locationID, ratingCount = 0; public boolean equals(Object o) { if(!(o instanceof ObjectLocation)) return false; ObjectLocation another = (ObjectLocation)o; if( locationID == another.locationID && ratingCount == another.ratingCount) return true; else return false; } public static void main(String[] args) { List<ObjectLocation> myLocations; ObjectLocation findThisLocation; ObjectLocation found; //Additional code here int index = myLocations.indexOf(findThisLocation); found = myLocations.get(index); int id = found.locationID; int rating = found.ratingCount; } } 的索引。然后提取该对象并使用其信息,如下面的代码所示:

{{1}}

答案 3 :(得分:0)

List<ObjectLocation> myLocations = new ArrayList<>();

int index =0;
        int particularId = 1;//!your Id
        int locationid = 0;
        int ratingcount = 0;
        for(int i =0; i < myLocations.size(); i++) {
            if(myLocations.get(i).locationID == particularId) {
                index = i;
                locationid = myLocations.get(i).locationID;
                ratingcount = myLocations.get(i).ratingCount;
            }            
        }

答案 4 :(得分:0)

对于Java 8,我会使用(不改变数据结构上的任何内容,比如使用Map代替或知道列表中的排序):

Optional<ObjectLocation> found = myLocations.stream()
  .filter(location -> location.locationID == particularLocationID)
  .findAny();
if (found.isPresent() {
  int ratingCount = found.get();
  …
}

当您需要更高的单次搜索效果时,您可以尝试使用parallelStream()代替stream()