Commons Collections 简明教程

Apache Commons Collections - Subtraction

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 Substraction

CollectionUtils 的 subtract() 方法可用于获取新集合,方法是从其他集合中减去一个集合的对象。

subtract() method of CollectionUtils can be used to get the new collection by subtracting objects of one collection from other.

Declaration

以下是 org.apache.commons.collections4.CollectionUtils.subtract() 方法的声明:

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

public static <O> Collection<O> subtract(Iterable<? extends O> a, Iterable<? extends O> b)

Parameters

  1. a − The collection to subtract from, must not be null.

  2. b − The collection to subtract, must not be null.

Return Value

一个包含结果的新集合。

A new collection with the results.

Example

以下示例展示了 org.apache.commons.collections4.CollectionUtils.subtract() 方法的用法。我们将得到两个列表相减的结果。

The following example shows the usage of org.apache.commons.collections4.CollectionUtils.subtract() method. We’ll get the subtraction of two lists.

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("List 1 - List 2: "+ CollectionUtils.subtract(list1, list2));
   }
}

Output

执行以上代码时,应该看到以下输出 −

When you execute the above code, you should see the following output −

List 1: [A, A, A, C, B, B]
List 2: [A, A, B, B]
List 1 - List 2: [A, C]