TreeSet addAll() Method in Java
Last Updated :
12 Jun, 2023
The java.util.TreeSet.addAll(Collection C) method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order.
Syntax:
boolean addAll(Collection C)
Parameters: The parameter C is a collection of any type that is to be added to the tree set.
Return Value: The method returns true if it successfully appends the elements of the collection C to the TreeSet otherwise it returns False.
Below programs illustrate the Java.util.TreeSet.addAll() method:
Program 1 : Appending a tree set.
Java
import java.io.*;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String args[])
{
TreeSet<String> tree = new TreeSet<String>();
tree.add("Welcome");
tree.add("To");
tree.add("Geeks");
tree.add(" 4 ");
tree.add("Geeks");
tree.add("TreeSet");
System.out.println("TreeSet: " + tree);
TreeSet<String> tree_two = new TreeSet<String>();
tree_two.add("Hello");
tree_two.add("World");
tree.addAll(tree_two);
System.out.println("TreeSet: " + tree);
}
}
|
Output:
TreeSet: [4, Geeks, To, TreeSet, Welcome]
TreeSet: [4, Geeks, Hello, To, TreeSet, Welcome, World]
Program 2 : Appending an ArrayList.
Java
import java.io.*;
import java.util.TreeSet;
import java.util.ArrayList;
public class TreeSetDemo {
public static void main(String args[])
{
TreeSet<String> tree = new TreeSet<String>();
tree.add("Welcome");
tree.add("To");
tree.add("Geeks");
tree.add(" 4 ");
tree.add("Geeks");
tree.add("TreeSet");
System.out.println("TreeSet: " + tree);
ArrayList<String> collect = new ArrayList<String>();
collect.add("A");
collect.add("Computer");
collect.add("Portal");
tree.addAll(collect);
System.out.println("Final TreeSet: " + tree);
}
}
|
Output:
TreeSet: [4, Geeks, To, TreeSet, Welcome]
Final TreeSet: [4, A, Computer, Geeks, Portal, To, TreeSet, Welcome]
Share your thoughts in the comments
Please Login to comment...