Skip to content

Commit ba98dd8

Browse files
Create PriorityQueueDemo.java
1 parent b006f1e commit ba98dd8

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package learnCollections;
2+
3+
import java.util.Comparator;
4+
import java.util.PriorityQueue;
5+
6+
public class PriorityQueueDemo {
7+
public static void main(String[] args) {
8+
// Part of the Queue interface
9+
// order elements based on their natural ordering (for primitives lowest first)
10+
// custom comparator for customized ordering
11+
// does not allow null elements
12+
13+
// min-heap by default
14+
PriorityQueue<Integer> pq = new PriorityQueue<>();
15+
pq.add(15);
16+
pq.add(10);
17+
pq.add(30);
18+
pq.add(5);
19+
20+
while(!pq.isEmpty()) {
21+
System.out.println(pq.poll()); // 5, 10, 15, 30
22+
}
23+
24+
PriorityQueue<Integer> pq1 = new PriorityQueue<>(Comparator.reverseOrder()); // max-heap
25+
26+
PriorityQueue<Integer> pq2 = new PriorityQueue<>((a, b) -> a - b); // min-heap using lambda expression
27+
PriorityQueue<Integer> pq3 = new PriorityQueue<>((a, b) -> b - a); // max-heap using lambda expression
28+
}
29+
}

0 commit comments

Comments
 (0)