http://www.stehno.com/articles/java/jakartacommonspredicates.php
Before we go any farther, we need a Predicate to work with. The Predicate interface is pretty simple, containing only a single method to implement, so I will just show it below:
public class EvenIntegerPredicate implements Predicate {
public boolean evaluate(Object obj){
boolean accept = false;
if(obj instanceof Integer){
accept = ((Integer)obj).intValue() % 2 == 0;
}
return(accept);
}
}
The evaluate()
method is called for each element to be tested. In this case, the object must be an Integer implementation and have an even value to be accepted.
Select the Even Numbers
This case uses the select(Collection,Predicate)
method of the CollectionUtils
class. This method selects all elements from input collection which match the given predicate into an output collection.
Predicate evenPred = new EvenIntegerPredicate();
Collection nums = CollectionUtils.select(numbers,evenPred);
which will yield a new collection containing only the even numbers from the original list while the original list will remain unchanged.
Filter the Collection
This next method is good when you are able to reuse the original collection once it is filtered. The CollectionUtils.filter(Collection,Predicate)
method filters the collection by testing each element and removing any that the predicate rejects.
CollectionUtils.filter(numbers,new EvenIntegerPredicate());
No comments:
Post a Comment