In this post under Apache Collections, I will show with example the use of “selectRejected” method.
“selectRejected” is a static method available under “CollectionUtils” class.
It takes two arguments
1) input collection
2) predicate
In this method, the predicate is evaluated on each item of the collection and a new collection is returned which contains items from input collection that doesn’t meet the predicate criteria.
Below is the main example
Main class
package defaultPackage;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class Example18 {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>(0);
integerList.add(1);
integerList.add(2);
integerList.add(3);
integerList.add(4);
integerList.add(5);
integerList.add(6);
integerList.add(7);
integerList.add(8);
integerList.add(9);
integerList.add(10);
List<Integer> output = (List<Integer>) CollectionUtils.selectRejected(integerList, (data) -> {
return (data % 2) == 0;
});
output.forEach(System.out::println);
}
}
In the above main method, I have created a list of type integer and populated it.
Then at line 22, I created a predicate which checks for event integers only.
Now at line 22, I call “CollectionUtils” static method “selectRejected” and pass the input collection and predicate.
The result that is the output collection will have only odd integers.
Below is the output for your reference
Output
1
3
5
7
9