Queue interface in collections framework

java 1.5 version enhancements(Queue interface)

Queue interface specific methods

boolean offer(Object o); // --> Same as enqueue
// For seeing the first element.
Object peek(); // to return head(first) element of the queue. If queue is empty, this method returns null.
Object element(); // to return head(first) element of the queue. If queue is empty, this method raises RE: NoSuchElementException.
// For dequeue purposes
Object poll(); // to remove and return head element of the queue. If queue is empty then this method returns null.
Object remove(); // to remove and return head element of the queue. If queue is empty then this method raises RE: NoSuchElementException.

Priority Queue:

Constructors

1.

 PriorityQueue q = new PriorityQueue();

2.

PriorityQueue q = new PriorityQueue(int initialCapacity);

3.

PriorityQueue q = new PriorityQueue(int initialCapacity, Comparator c);

4.

PriorityQueue q = new PriorityQueue(Collection c);

5.

PriorityQueue q = new PriorityQueue(SortedSet s);

Implementation demo 1

import java.util.PriorityQueue;
public class PriorityQueueDemo {
    public static void main(String[] args){
        PriorityQueue priorityQueue = new PriorityQueue();
//        System.out.println(priorityQueue.peek());
//        System.out.println(priorityQueue.element());
        for(int i = 0; i <= 10; i++)priorityQueue.offer(i);
        System.out.println(priorityQueue);
        System.out.println(priorityQueue.poll()); // 0
        priorityQueue.offer(1);
        System.out.println(priorityQueue); // [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }
}

Important Note: Some platforms won’t provide proper support for thread priorities and PriorityQueue classes. That is the reason we may get non-sorted outputs.

Implementation demo 2

import java.util.Comparator;
import java.util.PriorityQueue;
public class PriorityQueueDemo1 {
    public static void main(String[] args){
        PriorityQueue priorityQueue = new PriorityQueue(6, new MyComparator8());
        priorityQueue.offer("L");
        priorityQueue.offer("B");
        priorityQueue.offer("Z");
        priorityQueue.offer("A");
        System.out.println(priorityQueue); // [Z, L, B, A]

    }
}
class MyComparator8 implements Comparator{
    @Override
    public int compare(Object o1, Object o2) {
        String s1 = o1.toString();
        String s2 = o2.toString();
        return s2.compareTo(s1);
    }
}

There is a support for double ended queues in java which is provided by Dequeue interface. For further reading please visit this link.