Java Program to Get the Union & Intersection of Two TreeSet


TreeSet is a class that implements Set interface in Java. In a tree set the elements are stored in sorted order as it is implemented internally using a sorted balanced tree called as binary search tree. The elements in the TreeSet are stored in ascending order by default. Union of sets contains all the elements from both sets.Intersection of sets contain all the elements which are commonly present in both sets. In this section, we will be discussing about how to get the union and intersection of two treesets using Java.

What are the Union and Intersection of Sets?

Union − The union of sets contains all the elements from either set A or set B or both. If an element is present in both sets then we just show it as only one occurrence in the resultant union set.

A={1,2,3,4}
B={3,4,5}
A union B ={1,2,3,4,5}

Intersection − Intersection of sets contain all the elements which are commonly present in both sets.

A={1,2,3,4}
B={3,4,5}  	
A intersection B={3,4}

We will now look into basic operations on treeset provided by Java and the syntax and usage of methods.

Basic Operations on TreeSet

Here, we will discuss regarding the basic operations that we can perform on TreeSet using in built methods provided by Java TreeSet Class.

add() − This method helps to add elements to the TreeSet. It accepts a parameter basically the type of elements stored in theTreeSet.

treeSetObject.add(element)

remove() − This method helps to remove elements from the TreeSet. The element passed to this method is removed from the TreeSet.

treeSetObject.remove("b"); // removes "b" from the set

clear() − This method helps to clear all elements from the TressSet.

treeSetObject.clear(); // removes all elements from set

contains() − This method helps to check whether an element which is passed as a parameter is present in the TrssSet. It returns boolean value. If the element is present it returns true else returns false.

boolean val = treeSetObject.contains(‘b’); // checks ‘b’ is present and returns boolean value

isEmpty() − This method helps to check whether the TreeSet is empty or not. It returns boolean value. If the treeset is empty is it returns true else returns false.

boolean val = treeSetObject.isEmpty(); // checks hashSet conatians elements or not  

addAll() − This method is used to add a collection of elements to other collection upon which it is called. It accepts a parameter of collection type from which it adds elements to the collection which it is called upon.

colletion_1.addAll(collection_2);

retainAll() − This method is used to retain the elements that are present in both the collections i.e., it compares the collection which this method is called upon with the collection which is passed as a parameter. It returns a boolean value. If the collection on which it is called upon is modified then it returns true else returns false.

boolean result  = collection_1.retainAll(collection_2);

Now, we discuss in detail about the code implementation of how to implement java code for finding Union and Intersection of Two TreeSets.

Approach 1: Using addAll() and retainAll()

In this approach, we will use the addAll() and retainAll() methods provided by java to find the union and intersection of two treesets.

Algorithm

  • Initialize two TreeSets namely s1, s2 by converting array elements to list using Arrays.asList().

  • Copy the s1 as union Treeset and add all the elements of s2 by using addAll() and print it.

  • Copy the s1 as intersection TreeSet and use retainAll() to find the common elements between s1 and s2 and print it.

Example

In this example, we create two tree objects s1, s2 and initialise them with values and then we create a new object of TreeSet called ‘union’ on s1 object and we use addAll() method to add the elements present in the s2 to get all the elements present in both sets s1 and s2 which is nothing but the union of two treesets s1 and s2. We create a new object of TreeSet called ‘intersection’ on s1 object and we use retainAll() method to get all the common elements from s1 and s2 treesets.

import java.util.*;

public class Main{
   public static void main(String[] args) {
      TreeSet<Integer> s1 = new TreeSet<>(Arrays.asList(2, 8, 7, 3));
      TreeSet<Integer> s2 = new TreeSet<>(Arrays.asList( 5, 2, 7));
      TreeSet<Integer> union = new TreeSet<>(s1);
      union.addAll(s2);
      System.out.println("Union Set : " + union);
      TreeSet<Integer> intersection = new TreeSet<>(s1);
      intersection.retainAll(s2);
      System.out.println("Intersection Set : " + intersection);
   }
}

Output

Union Set : [2, 3, 5, 7, 8]
Intersection Set : [2, 7]

Approach 2: Using Iteration Statements

In this approach, we will use the for-each loop provided by java and iterate over the two sets and add to another TreeSet for getting union of two TreeSets. For intersection, we loop over two TreeSets and find the common elements.

Algorithm

  • Initialize two TreeSets s1, s2 by converting array elements to list using Arrays.asList().

  • Create an empty TreeSet union and iterate through the s1 and s2 elements and add them to the union using add().

  • Create an empty TreeSet intersection and iterate through the s1 and using contains() find the elements of s2 present in s1 and if the element is present then add them to the intersection Treeset using add().

  • Print the union and intersection TreeSets.

Example

In this example, we create two tree objects s1, s2 and initialise them with values and then we create a new object of TreeSet called ‘union’ and using for-each loop we add all the elements to the set from both sets s1 and s2. We then create a new treeset named ‘intersection’ and using foreach loop we iterate over s1 and check whether that element is present in s2, if it is present we add to the ‘intersection’ treeset. We then print the both treesets.

import java.util.*;

public class Main {
   public static void main(String[] args) {
      TreeSet<Integer> s1 = new TreeSet<>(Arrays.asList(2, 8, 7, 3));
      TreeSet<Integer> s2 = new TreeSet<>(Arrays.asList(5, 2, 7));
      TreeSet<Integer> union = new TreeSet<>();
      for (Integer element : s1) {
         union.add(element);
      }
      for (Integer element : s2) {
         union.add(element);
      }
      TreeSet<Integer> intersection = new TreeSet<>();
      for (Integer element : s1) {
         if (s2.contains(element)) {
            intersection.add(element);
         }
      }
      System.out.println("Union: " + union);
      System.out.println("Intersection: " + intersection);
   }
}

Output

Union: [2, 3, 5, 7, 8]
Intersection: [2, 7]

Thus, in this article we have learned different approaches of finding the Union and Intersection of Two TreeSets using Java.

Updated on: 16-Aug-2023

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements