how to pass elements of one collection to another collection
Previous | Home | Next |
In the following example we will see how can we pass the elements of one collection to another collection using the ArrayList.
In this example we have created a class CollectionExample. For using ArrayList we have
to import the java.util package.
In this example we have used the main() method which contains the various operations that creates an ArrayList and show how
can we pass one collection to some other collection as a parameter.
In the following example we have created a class named CollectionExample. In this class we have created an ArrayList name al, in which we have added the elements using the add() method. We also created another ArrayList name al1 in which we have added some more elements. Then by using the addAll(Collectio coll) on the ArrrayList al we have added the elements of the ArrayList al1 to the ArrayList al. The following code snippet does that,
al.add(al1);
The above statement adds all the elements of the al1 to the ArrayList al.
package r4r.co.in;
import java.util.ArrayList;
import java.util.Iterator;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
ArrayList<String> al1=new ArrayList<String>();
al1.add("4");
al1.add("5");
al1.add("6");
al1.add("7");
ArrayList<String> al=new ArrayList<String>(); // creating an ArrayList named al
al.add("r4r"); // adding string objects to the arraylist
al.add("development");
al.add("tutorials");
al.add("shashi");
al.add("s/w engineer");
System.out.println("The size of the arraylist is: "+al.size()); // determining the length of the arraylist
al.remove(2); // removing the element at the index 2
al.add(2,"e-learning"); // adding the element at the index 2
al.set(1, "softwares"); // replacing the element contained at index 1 by sai
al.addAll(4,al1); // adding the collection al1 to the al starting from the index 4
System.out.println("The contents of the list are :"+al); // showing the contents of the arraylist
Iterator<String> itr=al.iterator(); // Invoking the Iterator on the arraylist al
itr.next(); // passing over the first element
itr.remove(); // removing the first element
System.out.println("The elements in the ArrayList after the deletion are as follows: ");
while(itr.hasNext()) // iterating over the list
{
System.out.println(itr.next()); // printing the remaining elements in the list
}
}
}
The Output of the above program is shown below as,
The size of the arraylist is: 5
The contents of the list are :[r4r, softwares, e-learning, shashi, 4, 5, 6, 7, s/w engineer]
The elements in the ArrayList after the deletion are as follows:
softwares
e-learning
shashi
4
5
6
7
s/w engineer
Previous | Home | Next |