目录

Commons Collections - Intersection

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

检查交叉口

CollectionUtils的intersection()方法可用于获取两个集合(交集)之间的公共对象。

声明 (Declaration)

以下是声明

org.apache.commons.collections4.CollectionUtils.intersection()方法

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

参数 (Parameters)

  • a - 第一个(子)集合,不能为空。

  • b - 第二个(超级)集合,不得为null。

返回值 (Return Value)

两个集合的交集。

例子 (Example)

以下示例显示了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));
   }
}

输出 (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]
↑回到顶部↑
WIKI教程 @2018