In this post, we will see CollectionUtils retainAll() example in Java. It returns a collection that contains all the elements in the collection that are also in retain list. We will see how to use CollectionUtils retainAll() method. We need to add the below dependency in maven to use org.apache.commons.collections4.CollectionUtils retainAll()
method. We can download the apache-commons maven dependency from here.
pom.xml changes
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
CollectionUtils retainAll() Example in Java
package com.javatute;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class CollectionUtilsRetainAllExample {
public static void main(String[] args) {
List<String> firstList = new ArrayList<>();
firstList.add("John");
firstList.add("Mark");
firstList.add("Mike");
firstList.add("Tom");
List<String> secondList = new ArrayList<>();
secondList.add("John");
secondList.add("Mark");
List<String> newList = (List<String>) CollectionUtils.retainAll(firstList, secondList);
System.out.println(newList);
}
}
Output is
[John, Mark]
What is the difference between CollectionUtils retainAll() and CollectionUtils removeall() in Java?
Suppose we have two lists list1 and list2, then retainAll() will delete all the elements of list1 that do not match in list2 whereas removeAll() will delete all the elements of list1 that match in list2.
package com.javatute.main;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class CollectionUtilsReverseArrayExample {
public static void main(String[] args) {
// Create first list
List<String> list1 = new ArrayList<>();
// add some element
list1.add("John");
list1.add("Mark");
list1.add("Smith");
list1.add("Twin");
// create second list
List<String> list2 = new ArrayList<>();
// add some element
list2.add("John");
list2.add("Mark");
List<String> retainAllList = (List<String>) CollectionUtils.retainAll(list1, list2);
System.out.println(retainAllList);
List<String> removeAllList = (List<String>) CollectionUtils.removeAll(list1, list2);
System.out.println(removeAllList);
}
}
Output is –
[John, Mark]
[Smith, Twin]
That’s all about CollectionUtils retainAll() Example in Java.
Related post