Home »
Java »
Java Programs
Java program to add non-common elements of one TreeSet into another TreeSet collection
Given two TreeSet collections, we have to add non-common elements of one TreeSet into another.
Submitted by Nidhi, on June 05, 2022
Problem Solution:
In this program, we will create two TreeSet collections with integer elements. Then we will add non-common elements of one TreeSet into another TreeSet collection using the addAll() method.
Program/Source Code:
The source code to add non-common elements of one TreeSet into another TreeSet collection is given below. The given program is compiled and executed successfully.
// Java program to add non-common elements of one TreeSet
// into other TreeSet collection
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) {
TreeSet < Integer > tree1 = new TreeSet < Integer > ();
TreeSet < Integer > tree2 = new TreeSet < Integer > ();
tree1.add(10);
tree1.add(20);
tree1.add(30);
tree2.add(10);
tree2.add(40);
tree2.add(50);
tree2.add(60);
System.out.println("TreeSet1 elements: " + tree1);
System.out.println("TreeSet2 elements: " + tree2);
tree1.addAll(tree2);
System.out.println("\nTreeSet1 elements: " + tree1);
System.out.println("TreeSet2 elements: " + tree2);
}
}
Output:
TreeSet1 elements: [10, 20, 30]
TreeSet2 elements: [10, 40, 50, 60]
TreeSet1 elements: [10, 20, 30, 40, 50, 60]
TreeSet2 elements: [10, 40, 50, 60]
Explanation:
In the above program, we imported the "java.util.*", "java.io.*" packages to use the TreeSet class. Here, we created a public class Main.
The Main class contains a main() method. The main() method is the entry point for the program. And, created two TreeSet collections tree1, tree2 and added integer elements using add() method. Then we added the non-common elements of the tree2 collection into the tree1 collection using the addAll() method and printed the updated tree sets.
Java TreeSet Programs »