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;
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 expressionresult is a List with a Sample typelist.parallelStream() instead of list.stream() (read this)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:
Object to Sample at each iterationSample[], you need extra code (as shown in my sample)Bonus: A nice blog article talking about how to find element in list.