Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 293
Jeevi Avatar asked Oct 30 '12 12:10

Jeevi


2 Answers

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!

like image 88
Esteve Avatar answered Oct 09 '22 04:10

Esteve


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<Sample> list = new ArrayList<Sample>(); List<Sample> 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.

like image 38
Yves M. Avatar answered Oct 09 '22 05:10

Yves M.