Commons-collections-intersection
提供:Dev Guides
Apache Commonsコレクション-交差点
Apache Commons CollectionsライブラリのCollectionUtilsクラスは、幅広いユースケースをカバーする一般的な操作のためのさまざまなユーティリティメソッドを提供します。 定型コードの記述を避けるのに役立ちます。 同様の機能がJava 8のStream APIで提供されるようになったため、このライブラリはjdk 8より前に非常に便利です。
交差点の確認
CollectionUtilsのintersection()メソッドを使用して、2つのコレクション間で共通オブジェクトを取得できます(交差)。
宣言
以下はの宣言です
- org.apache.commons.collections4.CollectionUtils.intersection()*メソッド
public static <O> Collection<O> intersection(Iterable<? extends O> a,
Iterable<? extends O> b)
パラメーター
- a -最初の(サブ)コレクションは、nullであってはなりません。
- b -2番目の(スーパー)コレクションは、nullであってはなりません。
戻り値
2つのコレクションの共通部分。
例
次の例は、org.apache.commons.collections4.CollectionUtils.intersection()メソッドの使用方法を示しています。 2つのリストの共通部分を取得します。
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]