CollectionUtils containsAny method

In this post under Apache Collections, I will explain with example the purpose of CollectionUtils “containsAny” method.

This method is used to compare two collections. It returns true if both the collections has atleast one element in common or else false.

Below is the main class for your reference

Main class

1  package defaultPackage;
2
3 import org.apache.commons.collections4.CollectionUtils;
4
5 import java.util.ArrayList;
6 import java.util.List;
7
8 public class Example9 {
9 public static void main(String[] args) {
10 List<Integer> intList1 = new ArrayList<>(0);
11 List<Integer> intList2 = new ArrayList<>(0);
12 List<Integer> intList3 = new ArrayList<>(0);
13
14 intList1.add(1);
15 intList1.add(2);
16 intList1.add(3);
17 intList1.add(4);
18
19 intList2.add(4);
20 intList2.add(5);
21 intList2.add(6);
22 intList2.add(7);
23
24 intList3.add(5);
25 intList3.add(6);
26 intList3.add(7);
27 intList3.add(8);
28
29 System.out.println("intList1 containsAny intList2: " + CollectionUtils.containsAny(intList1, intList2));
30 System.out.println("intList1 containsAny intList3: " + CollectionUtils.containsAny(intList1, intList3));
31 }
32 }

In the above code, I create 3 lists containing integers “intList1”, “intList2”, and “intList3”.

From line 14 to 27, I populate them.

At line 29, I compare “intList1” with “intList2” and the result is printed to console.

In this case, the method returns true as both “intList1” and “intList2” has one element common that is 4.

At line 30, I compare “intList1” with “intList3” and the result is printed to console.

In this case, the method returns fals as both “intList1” and “intList3” doesn’t have any element in common.

In this way, we can use CollectionUtils “containsAny” method.

Leave a comment