w3resource

Java: Add all the elements of a specified tree set to another tree set


3. Add Elements to Another TreeSet

Write a Java program to add all the elements of a specified tree set to another tree set.

Sample Solution:

Java Code:

import java.util.TreeSet;
public class Exercise3 {
  public static void main(String[] args) {
  TreeSet<String> tree_set1 = new TreeSet<String>();
  tree_set1.add("Red");
  tree_set1.add("Green");
  tree_set1.add("Orange");
  System.out.println("Tree set1: "+tree_set1);
  TreeSet<String> tree_set2 = new TreeSet<String>();
  tree_set2.add("Pink");
  tree_set2.add("White");
  tree_set2.add("Black");
  System.out.println("Tree set2: "+tree_set2);
   // adding treetwo to treeone
   tree_set1.addAll(tree_set2);
   System.out.println("Tree set1: "+tree_set1);
 }
}

Sample Output:

Tree set1: [Green, Orange, Red]                                        
Tree set2: [Black, Pink, White]                                        
Tree set1: [Black, Green, Orange, Pink, Red, White] 

Flowchart:

Flowchart: Add all the elements of a specified tree set to another tree set

For more Practice: Solve these Related Problems:

  • Write a Java program to merge two TreeSets of strings and then print the resulting sorted set.
  • Write a Java program to add all elements from one TreeSet to another using addAll() and then remove duplicates from the merged set.
  • Write a Java program to create two TreeSets, merge them, and then display only the elements that are common to both sets.
  • Write a Java program to join two TreeSets of integers and then compute the sum of all elements in the resulting set.

Go to:


PREV : Iterate TreeSet Elements.
NEXT : Reverse Order TreeSet.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.