Apache Commons Collections - 交集



Apache Commons Collections 庫的 CollectionUtils 類提供各種實用方法,用於覆蓋廣泛用例的常用操作。這有助於避免編寫樣板程式碼。此庫在 jdk 8 之前非常有用,因為 Java 8 的 Stream API 現在提供了類似的功能。

檢查交集

可以使用 CollectionUtils 的 intersection() 方法獲取兩個集合之間的公共物件(交集)。

宣告

以下是 org.apache.commons.collections4.CollectionUtils.intersection() 方法的宣告——

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

引數

  • a − 第一個(子)集合,不能為 null。

  • b − 第二個(超)集合,不能為 null。

返回值

兩個集合的交集。

例子

以下示例展示了 org.apache.commons.collections4.CollectionUtils.intersection() 方法的用法。我們將獲得兩個列表的交集。

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("Commons Objects of List 1 and List 2: " + CollectionUtils.intersection(list1, list2));
   }
}

輸出

執行程式碼時,將看到以下輸出——

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]
廣告