CollectionUtils select method

In this post under Apache Commons Collections, I will explain with example the purpose of “select” static method in “CollectionUtils” class.

This method is basically used to filter the collection based on defined predicate.

Below is an example of its usage

Main class

package defaultPackage;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class Example17 {
    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.select(integerList, (input)->{
            return (input % 2) == 0;
        });

        output.forEach(System.out::println);
    }
}

In the above code, we have created an integer list and populated it with values.

Then we calling “select” static method of “CollectionUtils” and passing the below data as arguments
1) the collection on which the predicate has to be applied
2) the predicate itself.

In our example we are filtering numbers which are not divisible by 2.

In this way we can use “select” static method of “CollectionUtils” class

Below is the output

Output

2
4
6
8
10

Leave a comment