Java Program to Get the Union & Intersection of Two TreeSet
The union of two TreeSets is a Set of all the elements present in the two TreeSets. As the set does not contain duplicate values, so the union of two TreeSets also does not have duplicate values. Union of two TreeSets can be done using the addAll() method from java.util.TreeSet. TreeSet stores distinct values in sorted order, so the union can be done using the addition of set2 to set1, the addAll() method adds all the values of set2 that not present in set1 in sorted order.
The intersection of two TreeSet is a Set of all the same elements of set1 and set2. The intersection of two TreeSets also does not contain duplicate values. The intersection of two TreeSets can be done using the retainAll() method from java.util.TreeSet. The retainAll() method removes all the elements that are not same in both the TreeSets.
Example:
Input : set1 = {10, 20, 30}
set2 = {20, 30, 40, 50}
Output: Union = {10, 20, 30, 40, 50}
Intersection = {20, 30}
Input : set1 = {a, b, c}
set2 = {b, d, e}
Output: Union = {a, b, c, d, e}
Intersection = {b}
Below is the implementation:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
TreeSet<Integer> treeSet1 = new TreeSet<>();
treeSet1.add( 10 );
treeSet1.add( 20 );
treeSet1.add( 30 );
TreeSet<Integer> treeSet2 = new TreeSet<>();
treeSet2.add( 20 );
treeSet2.add( 30 );
treeSet2.add( 40 );
treeSet2.add( 50 );
System.out.println( "TreeSet1: " + treeSet1);
System.out.println( "TreeSet2: " + treeSet2);
TreeSet<Integer> union = new TreeSet<>();
union.addAll(treeSet2);
union.addAll(treeSet1);
System.out.println( "Union: " + union);
TreeSet<Integer> intersection = new TreeSet<>();
intersection.addAll(treeSet1);
intersection.retainAll(treeSet2);
System.out.println( "Intersection: " + intersection);
}
}
|
Output
TreeSet1: [10, 20, 30]
TreeSet2: [20, 30, 40, 50]
Union: [10, 20, 30, 40, 50]
Intersection: [20, 30]
Last Updated :
28 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...