Most efficient way to see if an ArrayList contains an object in Java

后端 未结 12 1140
孤城傲影
孤城傲影 2020-11-30 18:25

I have an ArrayList of objects in Java. The objects have four fields, two of which I\'d use to consider the object equal to another. I\'m looking for the most efficient wa

12条回答
  •  悲哀的现实
    2020-11-30 18:58

    Given your constraints, you're stuck with brute force search (or creating an index if the search will be repeated). Can you elaborate any on how the ArrayList is generated--perhaps there is some wiggle room there.

    If all you're looking for is prettier code, consider using the Apache Commons Collections classes, in particular CollectionUtils.find(), for ready-made syntactic sugar:

    ArrayList haystack = // ...
    final Object needleField1 = // ...
    final Object needleField2 = // ...
    
    Object found = CollectionUtils.find(haystack, new Predicate() {
       public boolean evaluate(Object input) {
          return needleField1.equals(input.field1) && 
                 needleField2.equals(input.field2);
       }
    });
    

提交回复
热议问题