English 中文(简体)
Commons Collections - Intersection
  • 时间:2024-09-17

Apache Commons Collections - Intersection


Previous Page Next Page  

CollectionUtils class of Apache Commons Collections pbrary provides various utipty methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This pbrary is very useful prior to jdk 8 as similar functionapties are now provided in Java 8 s Stream API.

Checking intersection

intersection() method of CollectionUtils can be used to get the common objects between two collections(intersection).

Declaration

Following is the declaration for org.apache.commons.collections4.CollectionUtils.intersection() method −


pubpc static <O> Collection<O> intersection(Iterable<? extends O> a, Iterable<? extends O> b)

Parameters

    a − The first (sub) collection, must not be null.

    b − The second (super) collection, must not be null.

Return Value

The intersection of the two collections.

Example

The following example shows the usage of org.apache.commons.collections4.CollectionUtils.intersection() method. We ll get the intersection of two psts.


import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;

pubpc class CollectionUtilsTester {
   pubpc static void main(String[] args) {
      //checking inclusion
      List<String> pst1 = Arrays.asList("A","A","A","C","B","B");
      List<String> pst2 = Arrays.asList("A","A","B","B");
      System.out.println("List 1: " + pst1);
      System.out.println("List 2: " + pst2);
      System.out.println("Commons Objects of List 1 and List 2: " + CollectionUtils.intersection(pst1, pst2));
   }
}

Output

When you run the code, you will see the following output −


List 1: [A, A, A, C, B, B]
List 2: [A, A, B, B]
Commons Objects of List 1 and List 2: [A, A, B, B]
Advertisements