how to add some other collection to the TreeSet using the collections in java
Previous | Home | Next |
In this example we will see how to add some other collection to the TreeSet.
For creating a TreeSet we have to import the java.util package in which we have the class java.util.TreeSet which contains the definition and various that can be performed on a TreeSet. In this example we have created a class named CollectionExample in which we have created a TreeSet and added some elements to it.
For adding the elements of some collection to the TreeSet, we use the addAll(Collection coll) method on the object of the TreeSet. The collections elements are appended in the same order in which they are returned by the collection's iterator. The syntax for using the addAll(Collection coll) method is ,
boolean addAll(Collection coll)
This method appends all of the elements in the specified Collection to the end of the created TreeSet in the order that they are returned by the specified Collection's Iterator.
In the following example we have created a TreeSet using the default constructor of the TreeSet. Then we added some elements to the TreeSet by invoking the add() method on the object of the TreeSet. Also we have created a linkedlist and added some elements to it. After that, we have added all the elements of the linkedlist to the TreeSet using the addAll(Collection coll) method on the object of the TreeSet ts.
The following statement of the given example does the very same function,ts.addAll(lst);
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args) throws ClassCastException, NullPointerException
{
// TODO Auto-generated method stub
try
{
TreeSet<Integer> ts=new TreeSet<Integer>();
ts.add(2);
ts.add(4);
ts.add(7);
ts.add(8);
ts.add(1);
ts.add(9);
System.out.println("The objects of the tree set are as follows: ");
System.out.println(ts);
List<Integer> lst=new LinkedList<Integer>();
lst.add(1);
lst.add(7);
lst.add(8);
lst.add(6);
System.out.println("The contents of the created linkedlist are: "+lst);
ts.addAll(lst);
System.out.println("Now the contents of the tree list after adding the LinkedList's contents are : "+ts);
}
catch(ClassCastException e)
{
System.out.println(e.getMessage());
}
catch(NullPointerException e)
{
System.out.println(e.getMessage());
}
}
}
The output of the above example is as follows:
The objects of the tree set are as follows:
[1, 2, 4, 7, 8, 9]
The contents of the created linkedlist are: [1, 7, 8, 6]
Now the contents of the tree list after adding the LinkedList's contents are : [1, 2, 4, 6, 7, 8, 9]
Previous | Home | Next |