Commons Collections 简明教程

Apache Commons Collections - Inclusion

Apache Commons Collections 库的 CollectionUtils 类提供各种实用方法,用于涵盖广泛使用场景的常见操作。它有助于避免编写样板代码。在 jdk 8 之前,该库非常有用,因为 Java 8 的 Stream API 中现在提供了类似的功能。

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

Checking sublist

CollectionUtils 的 isSubCollection() 方法可用于检查集合是否包含给定的集合。

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() 方法 −

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

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

Parameters

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

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

Return Value

当且仅当 a 是 b 的子集合时为 True。

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

Example

以下示例展示了 org.apache.commons.collections4.CollectionUtils.isSubCollection() 方法的用法。我们将检查一个列表是否是另一个列表的一部分。

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

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

public class CollectionUtilsTester {
   public static void main(String[] args) {
      //checking inclusion
      List<String> list1 = Arrays.asList("A","A","A","C","B","B");
      List<String> list2 = Arrays.asList("A","A","B","B");
      System.out.println("List 1: " + list1);
      System.out.println("List 2: " + list2);
      System.out.println("Is List 2 contained in List 1: " + CollectionUtils.isSubCollection(list2, list1));
   }
}

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