Write a Java program to add non-common elements of one TreeSet into another TreeSet collection


This is a Java program that demonstrates how to find the non-common elements between two TreeSet objects.

  • The program first creates two TreeSet objects called num1 and num2 and adds several string elements to them using the add() method.
  • Then, the program uses the addAll() method to add all the elements of num2 to num1. This causes num1 to now contain all the elements from both sets.
  • Finally, the program uses the removeAll() method to remove all the elements that are common between num1 and num2. This effectively leaves only the non-common elements in num1.
  • The program then prints the contents of both TreeSet objects to the console to show that num1 now only contains the non-common elements.

Source Code

import java.io.*;
import java.util.*;
public class NonCommon_Element
{
	public static void main(String args[])
	{
		TreeSet <String> num1 = new TreeSet <String>();
		num1.add("Blue");
		num1.add("Yellow");
		num1.add("Red");
		num1.add("Green");
		num1.add("White");		
 
		TreeSet <String> num2 = new TreeSet <String>();
		num2.add("Orange");
		num2.add("Yellow");
		num2.add("Green");
		num2.add("Pink");
 
		System.out.println("TreeSet 1 Elements : " + num1);
		System.out.println("TreeSet 2 Elements : " + num2);
 
		num1.addAll(num2);
		System.out.println("\nTreeSet 1 Elements : " + num1);
		System.out.println("TreeSet 2 Elements : " + num2);
	}
}

Output

TreeSet 1 Elements : [Blue, Green, Red, White, Yellow]
TreeSet 2 Elements : [Green, Orange, Pink, Yellow]

TreeSet 1 Elements : [Blue, Green, Orange, Pink, Red, White, Yellow]
TreeSet 2 Elements : [Green, Orange, Pink, Yellow]