How to search in a List of Java object

前端 未结 5 1341
耶瑟儿~
耶瑟儿~ 2020-11-27 16:21

I have a List of object and the list is very big. The object is

class Sample {
    String value1;
    String value2;
    String value3;
    String value4;
          


        
5条回答
  •  孤独总比滥情好
    2020-11-27 16:52

    Using Java 8

    With Java 8 you can simply convert your list to a stream allowing you to write:

    import java.util.List;
    import java.util.stream.Collectors;
    
    List list = new ArrayList();
    List result = list.stream()
        .filter(a -> Objects.equals(a.value3, "three"))
        .collect(Collectors.toList());
    

    Note that

    • a -> Objects.equals(a.value3, "three") is a lambda expression
    • result is a List with a Sample type
    • It's very fast, no cast at every iteration
    • If your filter logic gets heavier, you can do list.parallelStream() instead of list.stream() (read this)


    Apache Commons

    If you can't use Java 8, you can use Apache Commons library and write:

    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.collections.Predicate;
    
    Collection result = CollectionUtils.select(list, new Predicate() {
         public boolean evaluate(Object a) {
             return Objects.equals(((Sample) a).value3, "three");
         }
     });
    
    // If you need the results as a typed array:
    Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);
    

    Note that:

    • There is a cast from Object to Sample at each iteration
    • If you need your results to be typed as Sample[], you need extra code (as shown in my sample)



    Bonus: A nice blog article talking about how to find element in list.

提交回复
热议问题