I have a list of items, and I want to find a list of items that have the boolean property (field variable) x=true
.
I know that this can be accomplished by iteration, but I was looking for a common method to do that in commons library like Apache Commons.
Java provides Iterator and ListIterator classes to retrieve the elements of the collection object. The hasNext() method of these interfaces returns true if the collection object has next element else it returns false. The next() methods of the Iterator and ListIterator returns the next element of the collection.
To find an element matching specific criteria in a given list, we: invoke stream() on the list. call the filter() method with a proper Predicate. call the findAny() construct, which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists.
List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.
You could use apache commons collection implementing a Predicate for it.
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html
Sample:
package snippet;
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
public class TestCollection {
public static class User {
private String name;
public User(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [name=" + name + "]";
}
}
public static void main(String[] args) {
Collection<User> users = Arrays.asList(new User("User Name 1"), new User("User Name 2"), new User("Another User"));
Predicate predicate = new Predicate() {
public boolean evaluate(Object object) {
return ((User) object).getName().startsWith("User");
}
};
Collection filtered = CollectionUtils.select(users, predicate);
System.out.println(filtered);
}
}
A few sample can be found here: http://apachecommonstipsandtricks.blogspot.de/2009/01/examples-of-functors-transformers.html
And if you need something more generic, like inspect a value of a specific field or property you could do something like:
public static class MyPredicate implements Predicate {
private Object expected;
private String propertyName;
public MyPredicate(String propertyName, Object expected) {
super();
this.propertyName = propertyName;
this.expected = expected;
}
public boolean evaluate(Object object) {
try {
return expected.equals(PropertyUtils.getProperty(object, propertyName));
} catch (Exception e) {
return false;
}
}
}
That could compare a specific property to a expected value, and the use would be something like:
Collection filtered = CollectionUtils.select(users, new MyPredicate("name", "User Name 2"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With