Java Queue

Posted in /  

Java Queue

Ramya Shankar
Last updated on June 16, 2024

    In Java, Queues are used for pushing in data and retrieving it later. Queue follows the principle of FIFO i.e. First In First Out. In this article, we will discuss the most important methods of Java Queues and give a good amount of Java Queue examples to further the learning process.

    How to use Java Queue with Examples

    Queue is an ordered list of java objects where elements can be added at the end of the queue and removed from the first. The insertion order is not necessarily retained. Queue is an interface so to use the methods, we need a class that implements these methods. The most common classes that use Queue are LinkedList and PriorityQueue. To create a queue object, use the add method. To remove the head, we can use poll() or remove() methods. Here is a Java Queue example that shows adding and removing queue operations:

    Queue<String> qSample = new PriorityQueue<String>();
    //Lets add some elements
    System.out.println("Queue elements: " + qSample);
    System.out.println("initial Q size: "+qSample.size());
    // view the head of the queue
    //view and remove the head of the queue
    System.out.println("q size: " + qSample.size());
    System.out.println("Queue elements after removing head: " + qSample);
    //To remove a particular item, use the remove method
    System.out.println("Removing duplicate entry...." + qSample.remove("one"));
    // we can also remove the head using remove() without any parameter
    System.out.println("Removing head using remove()...." + qSample.remove());
    System.out.println("Final Queue elements: " + qSample);

    Note that we can do the same operations with LinkedList as well. Now, let us see how we can iterate through the Java Queue items.

    Iterator<String> qItr = qSample.iterator();

    Note that we have to import the following for the program to run:

    import java.util.Iterator;
    import java.util.PriorityQueue;
    import java.util.Queue;


    In this article, we have discussed the basic queue operations. Both PriorityQueue and LinkedList are not thread-safe, hence we can also use PriorityBlockingQueue, which is an unbounded Queue. Due to this, Blocking queues may throw OutOfMemory errors if the resources are exhausted.

    People are also reading:

    Leave a Comment on this Post