Using a Queue in java

problem

You wish to use the Queue data structure in Java. It is a FIFO – First In First Out data structure meaning the first item that is added is firstly retrieved. Analogous to a queue of people standing to get a ticket at the cinema.

SOLUTION - LinkedList

Java comes with the Queue but it’s an abstract class, meaning we cannot instantiate it. In this post we will see how to use two of its implementations. The LinkedList in the example below:

				
					 Queue<String> codes = new LinkedList<>();

codes.add("abc");
codes.add("xyz");
codes.add("klm");
				
			

LinkedList is used to instantiate our queue. The queue is a Generic class and in this case we specified it’s holding Strings that represent some hypothetical codes.

Simply adding items by using the add() method. Note: duplicated values are allowed.

running

Let’s simply print the queue using the console output:

QueueExample.java
				
					package com.programmerabroad;

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

public class QueueExample {

    public static void main(String[] args) {

        Queue<String> codes = new LinkedList<>();

        codes.add("abc");
        codes.add("xyz");
        codes.add("klm");

        System.out.println(codes);
    }
}
				
			
output
				
					[abc, xyz, klm]
				
			

When we use an object as an argument to the println() method, automatically invokes the toString() method. In this case is quite helpful as it prints all the contents without us needing to use an iteration.

SOLUTION - PriorityQueue

Another one way of instantiating a Queue is by using a PriorityQueue. For example:

				
					Queue<String> ids = new PriorityQueue<>();

    ids.add("1");
    ids.add("2");
    ids.add("3");
    ids.add("3");

    System.out.println(ids);
				
			
output
				
					[1,2,3,3]
				
			

As you can see, duplicates are allowed in this implementation too.

retrieving items
To retrieve an item from the queue we can use the poll() method. This method is returning the head of the queue and removes it too. If the queue is empty, it will return null.
For example:
				
					System.out.println(ids.poll()); //retrieve head and remove it

				
			
Alternative
				
					String head = ids.peek(); // retrieve head but doesn't remove it
				
			
removing items
				
					String head = ids.remove(); //throws exception if empty
				
			

The method also can be used for retrieving items as it’s returning the head. It can be enclosed in a try-catch statement for error handling.

conclusion

In this post we saw how to use a Queue and instantiate it by using either a LinkedList or PriorityQueue. It is a First In First Out data structure meaning by design what we add first is then retrieved first. A helpful feature for problem solving. In contrast of the LIFO – Last In First Out data structures like Stack.

references
  • https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.