Collections

how to use peek() and poll() methods in LinkedList using the collections API
Previous Home Next

 

In this example we will see how to use peek() and poll() methods defined in the List Interface on the LinkedList.

In this example we have created a class CollectionExample. For using LinkedList we have
to import the java.util package.
 In this example we have use the following methods,
peek()
This method retrieves  the head i.e the starting element of this list.
    
poll()
This method retrieves  and removes the starting(head) element of this list.

In this example we have created a LinkedList named list and then on the object that LinkedList i.e list we have applied the peek() method, which gives the head element of the list. After that we have applied the poll() method on the list which removes the head element from the list.

list.peek();
list.poll();
The above statements uses the peek() and poll() on the list in the given example.

 
package r4r.co.in;

import java.util.*;
import java.util.Iterator;
import java.util.List;
import java.util.Collection;


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 peek method retruns :"+list.peek()); // this retrieves the first element i.e. head of linked list
System.out.println("The poll method returns :"+list.poll()); // this retrieves and removes the first element i.e. head of the LinkedList
System.out.println("The contents of the list are as follows: ");

ListIterator<Object> ltr=list.listIterator(); // Invoking the ListIterator on the list for iterating through the list
while(ltr.hasNext())
{
System.out.println(ltr.next()); // displaying the contents of the list
}


}


}
The output of the above program will be displayed as:

The peek method retruns :1
The poll method returns :1
The contents of the list are as follows:
2
r4r
shashi
s/w engineer

Previous Home Next