Queue in Java

Queue

  1. Used when we have to use arranged in order of process.
  2. Queue interface extends collection, so it supports all methods of collection like list and set.
  3. It supports methos of collection and add, offer, remove, poll peek also.

Priority Queue

  1. Elements are sorted and in natural order.
package QueueInterface;

import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

class StringLengthComparator implements Comparator<String> {

	@Override
	public int compare(String o1, String o2) {
		// TODO Auto-generated method stub
		return Integer.compare(o1.length(), o2.length());
	}

}

public class QueueClass {

	public static void main(String[] args) {

		QueueClass qc = new QueueClass();
		// creating queue
		Queue<String> queue = new PriorityQueue<>();
		queue.offer("Apple");
		queue.addAll(List.of("Zebra", "Cat", "Dog", "Owl"));

		System.out.println("Queue is : " + queue);
		// O/P : Queue is : [Apple, Dog, Cat, Zebra, Owl]
		// it is in sorted order

		// Moving head in forward direction
		queue.poll();
		System.out.println("Queue is : " + queue);
		// O/P Queue is : [Cat, Dog, Owl, Zebra]

		// creating queue using comparator
		qc.queueUsingComparator();
	}

	public void queueUsingComparator() {
		Queue<String> queue = new PriorityQueue<>(new StringLengthComparator());
		queue.offer("Apple");
		queue.addAll(List.of("Zebra", "Cat", "Dog", "Owl"));
		System.out.println("Queue using StringLengthComparator is : " + queue);
		System.out.println(queue.poll());
		System.out.println(queue.poll());
		System.out.println(queue.poll());
		System.out.println(queue.poll());
		System.out.println(queue.poll());

		/*
		 * O/P is Queue using StringLengthComparator is : [Cat, Dog, Apple, Zebra, Owl]
		 * Cat Owl Dog Apple Zebra
		 * 
		 * here lower length is processed first and then higher length
		 */

	}
}

Tags: No tags

Leave A Comment

Your email address will not be published. Required fields are marked *