How to search in a List of Java object

前端 未结 5 1334
耶瑟儿~
耶瑟儿~ 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:59

    You can give a try to Apache Commons Collections.

    There is a class CollectionUtils that allows you to select or filter items by custom Predicate.

    Your code would be like this:

    Predicate condition = new Predicate() {
       boolean evaluate(Object sample) {
            return ((Sample)sample).value3.equals("three");
       }
    };
    List result = CollectionUtils.select( list, condition );
    

    Update:

    In java8, using Lambdas and StreamAPI this should be:

    List result = list.stream()
         .filter(item -> item.value3.equals("three"))
         .collect(Collectors.toList());
    

    much nicer!

提交回复
热议问题