Skip to content
Advertisement

How to search in a List of Java object

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;
    String value5;
 }

Now I have to search for a specific value of an object in the list. Say if value3=='three' I have to return those objects (My search is not always based on value3)

The list is

List<Sample> list = new ArrayList<Sample>();

What is the efficient way of doing it?

Thanks.

Advertisement

Answer

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<Sample> result = list.stream()
     .filter(item -> item.value3.equals("three"))
     .collect(Collectors.toList());

much nicer!

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement