-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathPriorityQueueExample.java
57 lines (49 loc) · 1.66 KB
/
PriorityQueueExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Java program to demonstrate working of priority queue in Java
import java.util.*;
class Example
{
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<String> pQueue =
new PriorityQueue<String>();
// Adding items to the pQueue using add()
pQueue.add("C");
pQueue.add("C++");
pQueue.add("Java");
pQueue.add("Python");
// Printing the most priority element
System.out.println("Head value using peek function:"
+ pQueue.peek());
// Printing all elements
System.out.println("The queue elements:");
Iterator itr = pQueue.iterator();
while (itr.hasNext())
System.out.println(itr.next());
// Removing the top priority element (or head) and
// printing the modified pQueue using poll()
pQueue.poll();
System.out.println("After removing an element" +
"with poll function:");
Iterator<String> itr2 = pQueue.iterator();
while (itr2.hasNext())
System.out.println(itr2.next());
// Removing Java using remove()
pQueue.remove("Java");
System.out.println("after removing Java with" +
" remove function:");
Iterator<String> itr3 = pQueue.iterator();
while (itr3.hasNext())
System.out.println(itr3.next());
// Check if an element is present using contains()
boolean b = pQueue.contains("C");
System.out.println ( "Priority queue contains C " +
"or not?: " + b);
// Getting objects from the queue using toArray()
// in an array and print the array
Object[] arr = pQueue.toArray();
System.out.println ( "Value in array: ");
for (int i = 0; i<arr.length; i++)
System.out.println ( "Value: " + arr[i].toString()) ;
}
}