how to add a LinkedList to another LinkedList using Collections
Previous | Home | Next |
In this example we will see how can we add the elements of one LinkedList to the another LinkedList using the collections.
In this example we have created a class CollectionExample. For using LinkedList we have
to import the java.util package.
For adding all the elements of a LinkedList to another LinkedlList we use the addAll(Collection coll) method on the LinkedList object to which the coll has to be added. The syntax of the addAll method is given as:
addAll(Collection coll)
This method appends all of the elements of the specified collection to the end of the LinkedList, and in the oorder they are returned by the specified collection's iterator.
In this example we have created two LinkedLists namely list and stringlist. In both of the lists we have added some elements. Then we have added all the elements of the stringlist to the list by using addAll method on the list. This statement does the very same in the following example:list.addAll(stringlist);
package r4r.co.in;
import java.util.*;
import java.util.ListIterator;
public class CollectionExample {
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
LinkedList<Object> list=new LinkedList<Object>(); // creating a LinkedList of Object type elements
list.add(1); // adding integer values to the LinkedList
list.add(2);
list.add("r4r"); // adding String values to the LinkedList
list.add("shashi");
list.add("s/w engineer");
System.out.println("The contents of the object list are :");
ListIterator<Object> ltr=list.listIterator();
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}
LinkedList<String> stringlist=new LinkedList<String>(); // created a new list of String type
stringlist.add("This");
stringlist.add("is");
stringlist.add("good");
stringlist.add("example");
System.out.println("The elements of the created string list are: ");
System.out.println(stringlist); //displaying the contents of the stringlist thus created
list.addAll(stringlist); // Adding the whole list String stringlist to the end of the Object list by using addAll(Collection coll) method
ltr=list.listIterator(); // Invoking the ListIterator on the list for iterating through the list
System.out.println("The contents of the added list are as follows :");
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the resulted list
}
}
}
The output will be the following :
The contents of the object list are :
1
2
r4r
shashi
s/w engineer
The elements of the created string list are:
[This, is, good, example]
The contents of the added list are as follows :
1
2
r4r
shashi
s/w engineer
This
is
good
example
Previous | Home | Next |