English 中文(简体)
Commons Collections - Inclusion
  • 时间:2024-11-05

Apache Commons Collections - Inclusion


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 subpst

isSubCollection() method of CollectionUtils can be used to check if a collection contains the given collection or not.

Declaration

Following is the declaration for

org.apache.commons.collections4.CollectionUtils.isSubCollection() method −


pubpc static boolean isSubCollection(Collection<?> a, Collection<?> b)

Parameters

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

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

Return Value

True if and only if a is a sub-collection of b.

Example

The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isSubCollection() method. We ll check a pst is part of another pst or not.


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("Is List 2 contained in List 1: " + CollectionUtils.isSubCollection(pst2, pst1));
   }
}

Output

You will receive the following output −


List 1: [A, A, A, C, B, B]
List 2: [A, A, B, B]
Is List 2 contained in List 1: true
Advertisements