The org.apache.commons.collections4.CollectionUtils intersection() method is used to return common elements from two lists. It checks for null as well as the size of collections. The CollectionUtils intersection() is a static method, which accepts Collection as a parameter.
Note – The order of the elements doesn’t matter to check equality i.e it will check for the same elements, the order can be different.
The intersection()
method is defined as below.
public static <O> Collection<O> intersection(Iterable<? extends O> a, Iterable<? extends O> b)
Let’s see an example of org.apache.commons.collections4.CollectionUtils
method.intersection
()
package com.javatute;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class CollectionsUtilIsIntersection {
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");
list2.add("Smith");
list2.add("Twin");
list2.add("James");
list2.add("Ket");
System.out.println(CollectionUtils.intersection(list1, list2));
}
}
Output:- [Smith, John, Mark, Twin]
That’s all about CollectionUtils intersection() Example in Java.
Related post.