Java Collections – Queue

Queue (Interface):-

Child interface of collection. If we want to represent a group of individual object prior to processing then we should go for queue.

For Eg:- Before sending a mail, for all mail ids  same order mails should be delivered.(FIFO-FIRST IN FIRST OUT). For this requirement queue concept is the best choice.

Following Queue implementations in the Java Collections API:

  • java.util.LinkedList
  • java.util.PriorityQueue

LinkedList is a standard queue implementation.

PriorityQueue stores its elements internally according to their natural order (if they implement Comparable), or according to a Comparator passed to the PriorityQueue.

We can create Queue instance in the following ways

Queue queueA = new LinkedList();
Queue queueB = new PriorityQueue();

Adding and Accessing Elements

To add elements to a Queue you call its add() method.

Queue queueA = new LinkedList();

queueA.add(“element 1”);
queueA.add(“element 2”);
queueA.add(“element 3”);

The order in which the elements added to the Queue are stored internally, depends on the implementation. The same is true for the order in which elements are retrieved from the queue.

You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the element() method.

Object firstElement = queueA.element();

You can also iterate all elements of a queue, instead of just processing one at a time.

Queue queueA = new LinkedList();

queueA.add(“element 0”);
queueA.add(“element 1”);
queueA.add(“element 2”);

//access via Iterator
Iterator iterator = queueA.iterator();
String element = (String);

//access via new for-loop
for(Object object : queueA) {
String element = (String) object;

When iterating the queue via its Iterator or via the for-loop (which also uses the Iterator behind the scene, the sequence in which the elements are iterated depends on the queue implementation.

Removing Elements

To remove elements from a queue, you call the remove() method. This method removes the element at the head of the queue. In most Queue implementations the head and tail of the queue are at opposite ends. It is possible, however, to implement the Queue interface so that the head and tail of the queue is in the same end. In that case you would have a stack.

Here is a remove example();

Object firstElement = queueA.remove();

Generic Queue

By default you can put any Object into a Queue, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a Queue.

Queue<MyObject> queue = new LinkedList<MyObject>();
This Queue can now only have MyObject instances inserted into it. You can then access and iterate its elements without casting them.

MyObject myObject = queue.remove();

for(MyObject anObject : queue){
//do someting to anObject…


Share :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Comments are closed