5.20. Performing Set Operations
Problem
You need to perform set operations to find the union, intersection, disjunction, and difference of two collections.
Solution
Use one of four CollectionUtils
methods to perform
set operations—union( )
,
intersection( )
, disjunction()
, and subtract( )
. Example 5-19 demonstrates
the use of these four methods with two
Collection
s.
Example 5-19. Using CollectionUtils union( ), intersection( ), disjunction( ), and subtract( )
import java.util.*; String[] arrayA = new String[] { "1", "2", "3", "3", "4", "5" }; String[] arrayB = new String[] { "3", "4", "4", "5", "6", "7" }; List a = Arrays.asList( arrayA ); List b = Arrays.asList( arrayB );Collection union = CollectionUtils.union( a, b );
Collection intersection = CollectionUtils.intersection( a, b );
Collection disjunction = CollectionUtils.disjunction( a, b );
Collection subtract = CollectionUtils.subtract( a, b );
Collections.sort( union ); Collections.sort( intersection ); Collections.sort( disjunction ); Collections.sort( subtract ); System.out.println( "A: " + ArrayUtils.toString( a.toArray( ) ) ); System.out.println( "B: " + ArrayUtils.toString( b.toArray( ) ) ); System.out.println( "Union: " + ArrayUtils.toString( union.toArray( ) ) ); System.out.println( "Intersection: " + ArrayUtils.toString( intersection.toArray( ) ) ); System.out.println( "Disjunction: " + ArrayUtils.toString( disjunction.toArray( ) ) ); System.out.println( "Subtract: " + ArrayUtils.toString( subtract.toArray( ) ) ); ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.