Queue Implementation in Java with Examples


You can implement Queue Data Structure (based on FIFO algorithm) in Java using the Queue interface or the LinkedList class.

Let us take a look at queue implementation using both of them:


    1. Implementing Queue using LinkedList

    package org.code2care.collections;
    
    import java.util.LinkedList;
    
    /**
     * Implementing Queue in Java using
     * LinkedList
     *
     * Author: Code2care.org
     * Date: 2nd May 2023
     * Version: v1.0
     *
     */
    public class JavaQueueLinkedListExample {
        public static void main(String[] args) {
    
            LinkedList<String> queue = new LinkedList<>();
    
            //Adding elements to queue
            queue.add("USA");
            queue.add("Japan");
            queue.add("China");
            queue.add("Canada");
            queue.add("India");
    
    
            //Printing the elements of the Queue
            for (String element : queue) {
                System.out.println(element);
            }
        }
    }
    
    USA
    Japan
    China
    Canada
    India

2. Implementing Queue using Queue Interface

    package org.code2care.java.sorting.algo;
    
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class QueueExampleUsingQueueInterface {
        
        public static void main(String[] args) {
    
    
            Queue<String> queue = new LinkedList<>();
    
            queue.add("China");
            queue.add("Japan");
            queue.add("USA");
            queue.add("Australia");
    
            for (String element : queue) {
                System.out.println(element);
            }
        }
    }
    
    China
    Japan
    USA
    Australia

You can remove elements from the queue using queue.remove() method.


Which one to choose?

    If you need a simple Queue implementation with basic functionality, make use of the Queue interface. If you need more advanced functions such as adding/removing elements from specific positions make use of the LinkedList implementation.

Java Queue using Queue Interface

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap