
how to use queue in java ?

import java.util.LinkedList;
import java.util.Queue;
public class MainDemo {
public void queueExample() {
Queue queue = new LinkedList();
queue.add("Java");
queue.add("DotNet");
queue.offer("PHP");
queue.offer("HTML");
System.out.println("remove: " + queue.remove());
System.out.println("element: " + queue.element());
System.out.println("poll: " + queue.poll());
System.out.println("peek: " + queue.peek());
}
public static void main(String[] args) {
new MainDemo().queueExample();
}
}
Output:-
remove: Java element: DotNet poll: DotNet peek: PHP
Description:- In the above code, we have implemented Queue by its subclass LinkedList.We have created a method QueueExample.Using the add()and offer() method, we have added elements to LinkedList. Then, we have used remove() and poll() methods to remove elements.
element(): This method retrieves the head of the queue.
offer(E o): This inserts the specified element into the queue.
peek(): This method retrieves the head of this queue, returning null if this queue is empty.
poll(): This method retrieves and removes the head of this queue, or return null if this queue is empty.
remove(): This method retrieves and removes the head of this queue.