Java TreeSet addAll(Collection c) Example

The addAll(Collection<? extends E> c) method of java.util.TreeSet class will simply inserts all of the elements in the specified collection to the end of the Set.

Signature

public boolean addAll(Collection<? extends E> c)

This method appends all the elements of a collection at the end of the set and will throw java.lang.NullPointerException when the specified collection is null and java.lang.ClassCastException if the elements provided cannot be compared with the elements currently in the set

Example

The following example shows the usage of java.util.TreeSet.addAll(c) method.

import java.util.TreeSet;

public class AddAllMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // Create treeSet1 object
        TreeSet treeSet1 = new TreeSet();
        
        //adding elements to TreeSet using add()
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        treeSet1.add("Element4");
        
        // Create treeSet2 object
        TreeSet treeSet2 = new TreeSet();
        treeSet2.add("String 1");
        treeSet2.add("String 2");
        treeSet2.add("String 3");
        treeSet2.add("String 4");
        
        //Printing the elements of the TreeSet1
        System.out.println("**Elements of the TreeSet1 before adding**");
        for(String val : treeSet1)
        {
            System.out.println(val);
        }
        
        //adding treeSet2 to treeSet1
        treeSet1.addAll(treeSet2);
        //Printing the elements of the TreeSet1
        System.out.println("**Elements of the TreeSet1 after adding**");
        for(String val : treeSet1)
        {
            System.out.println(val);
        }
    }
}

Output

**Elements of the TreeSet1 before adding**
Element1
Element2
Element3
Element4
**Elements of the TreeSet1 after adding**
Element1
Element2
Element3
Element4
String 1
String 2
String 3
String 4

Leave a Reply

Your email address will not be published. Required fields are marked *