CollectionUtils retainAll method

In this post under Apache Collections, I will show with example the purpose of “retainAll” method under “CollectionUtils” class.

The “retainAll” method takes two collections say “collection1” and “collection2” as arguments and returns a new collection.

The new collection will only contain elements that are present both in “collection1” and “collection2”.

Lets see a main class code for our example

Main class

package defaultPackage;

import org.apache.commons.collections4.CollectionUtils;

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

public class Example15 {
    public static void main(String[] args) {
        List<Integer> inputList = new ArrayList<>(0);
        inputList.add(1);
        inputList.add(2);
        inputList.add(3);
        inputList.add(4);

        List<Integer> evenInputList = new ArrayList<>(0);
        evenInputList.add(2);
        evenInputList.add(4);

        List<Integer> oddInputList = new ArrayList<>(0);
        oddInputList.add(1);
        oddInputList.add(3);

        List<Integer> outputList = (List<Integer>) CollectionUtils.retainAll(inputList, evenInputList);
        System.out.println(outputList);

        outputList = (List<Integer>)CollectionUtils.retainAll(inputList, oddInputList);
        System.out.println(outputList);
    }
}

In the above code, I created three list “inputList”, “evenInputList”, and “oddInputList”.

The “inputList” is populated with numbers, where as “evenInputList” is populated with only even numbers and “oddInputList” is populated with only odd numbers.

Now the call to “retainAll” at line 24, will return a new collection which will contain numbers present in both “inputList” and “evenInputList”. Which means the resulting collection will only contain
even numbers.

Now the call to “retainAll” at line 27, will return a new collection which will contain numbers present in both “inputList” and “oddInputList”. Which means the resulting collection will only contain
odd numbers.

In this way we can use “CollectionUtils” “retainAll” method.

Leave a comment