InterviewSolution
Saved Bookmarks
| 1. |
Priority Queue in Java |
|
Answer» The priority queue is a data structure in which elements are handled based on their priority. The priority heap is the basis of the priority queue. Also, priority queues are unbound queues and they do not allow NULL pointers. A program that demonstrates priority queue in Java is GIVEN as follows: import java.util.*; public CLASS Demo { public STATIC void main(String args[]) { PriorityQueue<String> p = new PriorityQueue<String>(); p.add("Apple"); p.add("Mango"); p.add("Orange"); p.add("Peach"); p.add("Guava"); System.out.println("The priority queue elements are:"); Iterator I1 = p.iterator(); while (i1.hasNext()) { System.out.println(i1.next()); } System.out.println("\nThe ELEMENT with highest priority is: " + p.peek()); p.poll(); System.out.println("\nThe priority queue elements after removing an element with poll function are:"); Iterator<String> i2 = p.iterator(); while (i2.hasNext()) { System.out.println(i2.next()); } } }The output of the above program is as follows: The priority queue elements are: Apple Guava Orange Peach Mango The element with highest priority is: Apple The priority queue elements after removing an element with poll function are: Guava Mango Orange Peach |
|