Easy Tutorial
❮ Java String Subsequence Java Arraylist Replaceall ❯

Java Example - Queue Usage

Java Examples

A queue is a special type of linear list that only allows deletion operations at the front of the list and insertion operations at the rear of the list.

The LinkedList class implements the Queue interface, so we can use LinkedList as a Queue.

The following example demonstrates the usage of a queue:

Main.java File

import java.util.LinkedList;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        // The add() and remove() methods throw exceptions on failure (not recommended)
        Queue<String> queue = new LinkedList<String>();
        // Adding elements
        queue.offer("a");
        queue.offer("b");
        queue.offer("c");
        queue.offer("d");
        queue.offer("e");
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("poll=" + queue.poll()); // Returns the first element and removes it from the queue
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("element=" + queue.element()); // Returns the first element
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("===");
        System.out.println("peek=" + queue.peek()); // Returns the first element
        for(String q : queue){
            System.out.println(q);
        }
    }
}

The output of the above code is:

a
b
c
d
e
===
poll=a
b
c
d
e
===
element=b
b
c
d
e
===
peek=b
b
c
d
e

Java Examples

❮ Java String Subsequence Java Arraylist Replaceall ❯