Create a queue using LinkedList class in Java

Java 8Object Oriented ProgrammingProgramming

To create a queue using LinkedList class, try the following −

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");

After that to print the elements, you need to use check a condition for Queue as shown below −

Object ob;
while ((ob = q.poll()) != null) {
   System.out.println(ob);
}

The following is an 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("Size = " + q.size());
      System.out.println("\nQueue elements...");
      Object ob;
      while ((ob = q.poll()) != null) {
         System.out.println(ob);
      }
   }
}

Output

Queue head = abc
Size = 8
Queue elements...
abc
def
ghi
jkl
mno
pqr
stu
vwx
raja
Published on 10-Jan-2019 08:09:40
Advertisements