how to add some other collection to the HashSet using collections in java
Previous | Home | Next |
In the following example we will see how can we add some other collection to the HashSet.
For creating a HashSet we have to import the java.util package in which the HashSet class is defined. In this example we have created a class name CollectionExample in which we created a HashSet and added various elements to it.
For adding the elements of a certain collection to the HashSet created we will use the following method,
boolean addAll(Collection coll)
This method appends all of the elements of the specified collection to the end of the HashSet in the same manner in which they are returned by the specified collection's iterator. If any element is duplicate then it will not be added to the HashSet.
In the given example we have created a HashSet named set and added some elements to it. We have also created an ArrayList named al and added some elements to it For adding all the elements of the ArrayList to the HashSet we use the addAll(Collection coll) method on the HashSet set. The following statement does the same in our example,set.addAll(al);
The above statement adds all the elements of the arraylist al to the HashSet set.
package r4r.co.in;
import java.util.*;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
ArrayList<Integer> al=new ArrayList<Integer>(); // creating an ArrayList of Integer elements
al.add(56); // adding elements to the arraylist
al.add(72);
al.add(97);
System.out.println("The contents of the ArrayList are: "+al);
HashSet<Integer> set=new HashSet<Integer>(); // creating a HashSet named set
set.add(1); // adding elements to the HashSet
set.add(3);
set.add(4);
set.add(5);
set.add(7);
set.add(1);
set.add(4);
set.add(7);
System.out.println("The contents of the set are:"); //displaying the contents of the HashSet
System.out.println(set);
set.addAll(al); // Adding the ArrayList to the HashSet set
System.out.println("The contents of set after adding Arraylist is: "+set); // displaying the resultant collection HashSet
}
}
The output of the above program is as follows:
The contents of the ArrayList are: [56, 72, 97]
The contents of the set are:
[1, 3, 4, 5, 7]
The contents of set after adding Arraylist is: [1, 3, 4, 5, 97, 7, 56, 72]
Previous | Home | Next |