Usage of element() method of Queues in Java


The element() method in Java Queues is used to return the element at the front of the container and does not remove it.

The following is an example. Firstly, create a Queue and add some elements −

Queue<String> q = new LinkedList<String>();
q.offer("abc");
q.offer("def");
q.offer("ghi");
q.offer("jkl");
q.offer("mno");
q.offer("pqr");
q.offer("stu");
q.offer("vwx");

Now use the element() method as shown below −

System.out.println("Queue head = " + q.element());

The following is the complete example −

Example

 Live Demo

import java.util.LinkedList;
import java.util.Queue;
public class Demo {
   public static void main(String[] args) {
      Queue<String> q = new LinkedList<String>();
      q.offer("abc");
      q.offer("def");
      q.offer("ghi");
      q.offer("jkl");
      q.offer("mno");
      q.offer("pqr");
      q.offer("stu");
      q.offer("vwx");
      System.out.println("Queue head = " + q.element());
      System.out.println("Removing element from queue = " + q.remove());
      System.out.println("Queue head now = " + q.element());
      System.out.println("
Remaining Queue elements...");       Object ob;       while ((ob = q.poll()) != null) {          System.out.println(ob);       }    } }

Output

Queue head = abc
Removing element from queue = abc
Queue head now = def
Remaining Queue elements...
def
ghi
jkl
mno
pqr
stu
vwx

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

581 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements