CodesJava

Easy learning with example program codes

PriorityQueue in java


PriorityQueue:

PriorityQueue extends AbstactQueue. PriorityQueue is a type of queue but not provide the FIFO facility to its elements. It not allows the null elements.

PriorityQueue example:

PriorityQueueTest.java

import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
 
/**
 * This class is used to show the 
 * PriorityQueue functionality.
 * @author codesjava
 */
public class PriorityQueueTest {
	public static void main(String args[]){
		//Create PriorityQueue  object.
		Queue priorityQueue  = new PriorityQueue();
 
		//Add objects to the PriorityQueue .
		priorityQueue.add("Gourav");
		priorityQueue.add("Neeraj");
		priorityQueue.add("Deepak");
		priorityQueue.add("Mohan");
		priorityQueue.add("Parmender");
 
		//Print the PriorityQueue object.
		System.out.println("HasPriorityQueue elements:");
		System.out.println(priorityQueue);
 
		//Print the PriorityQueue elements using iterator.
		Iterator iterator1=priorityQueue.iterator();
		System.out.println("PriorityQueue elements " +
				"using iterator:");
		while(iterator1.hasNext()){  
		   System.out.println(iterator1.next());  
		}
 
		//Print the head element of the PriorityQueue
		System.out.println("Head element: " 
				+ priorityQueue.element());
		System.out.println("Head element: " 
				+ priorityQueue.peek());
 
		//Remove the head element of the PriorityQueue
		priorityQueue.poll();
		priorityQueue.remove();
 
		//Print the PriorityQueue object.
		System.out.println("HasPriorityQueue elements " +
				"after manipulation:");
		System.out.println(priorityQueue);
 
		//Print the PriorityQueue elements using iterator.
		Iterator iterator2=priorityQueue.iterator();
		System.out.println("PriorityQueue elements after " +
				"manipulation using iterator:");
		while(iterator2.hasNext()){  
		   System.out.println(iterator2.next());  
		}
	}
}

Output:

HasPriorityQueue elements:
[Deepak, Mohan, Gourav, Neeraj, Parmender]
PriorityQueue elements using iterator:
Deepak
Mohan
Gourav
Neeraj
Parmender
Head element: Deepak
Head element: Deepak
HasPriorityQueue elements after manipulation:
[Mohan, Neeraj, Parmender]
PriorityQueue elements after manipulation using iterator:
Mohan
Neeraj
Parmender

Download this example.
 
Next Topic: ArrayDeque in java with example.
Previous Topic: TreeMap in java with example.



Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki