Open In App

Java Program to Get the Union & Intersection of Two TreeSet

Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to Get the Union
//& Intersection of Two TreeSet
  
import java.util.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // New TreeSet1
        TreeSet<Integer> treeSet1 = new TreeSet<>();
  
        // Add elements to treeSet1
        treeSet1.add(10);
        treeSet1.add(20);
        treeSet1.add(30);
  
        // New TreeSet1
        TreeSet<Integer> treeSet2 = new TreeSet<>();
  
        // Add elements to treeSet2
        treeSet2.add(20);
        treeSet2.add(30);
        treeSet2.add(40);
        treeSet2.add(50);
  
        // Print the TreeSet1
        System.out.println("TreeSet1: " + treeSet1);
  
        // Print the TreeSet1
        System.out.println("TreeSet2: " + treeSet2);
  
        // New TreeSet
        TreeSet<Integer> union = new TreeSet<>();
  
        // Get a Union using addAll() method
        union.addAll(treeSet2);
        union.addAll(treeSet1);
        // Print the Union
        System.out.println("Union: " + union);
  
        // New TreeSet
        TreeSet<Integer> intersection = new TreeSet<>();
        intersection.addAll(treeSet1);
        intersection.retainAll(treeSet2);
        // Print the intersection
        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
Previous
Next
Share your thoughts in the comments
Similar Reads