Skip to content

Commit 0f93aa5

Browse files
author
Rajeev Kumar Singh
committed
priority queue examples
1 parent f5c5a3d commit 0f93aa5

File tree

2 files changed

+42
-20
lines changed

2 files changed

+42
-20
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,9 @@
1-
import java.util.Comparator;
21
import java.util.PriorityQueue;
32

43
public class CreatePriorityQueueExample {
54
public static void main(String[] args) {
6-
Comparator<String> stringLengthComparator = new Comparator<String>() {
7-
@Override
8-
public int compare(String s1, String s2) {
9-
return s1.length() - s2.length();
10-
}
11-
};
12-
13-
/*
14-
The above Comparator can also be created using lambda expression like this =>
15-
Comparator<String> stringLengthComparator = (s1, s2) -> {
16-
return s1.length() - s2.length();
17-
};
18-
19-
The above statement can be shortened even further like this =>
20-
Comparator<String> stringLengthComparator = Comparator.comparingInt(String::length);
21-
*/
22-
23-
// Create a Priority Queue with a custom Comparator
24-
PriorityQueue<String> namePriorityQueue = new PriorityQueue<>(stringLengthComparator);
5+
// Create a Priority Queue
6+
PriorityQueue<String> namePriorityQueue = new PriorityQueue<>();
257

268
// Add items to a Priority Queue (ENQUEUE)
279
namePriorityQueue.add("Lisa");
@@ -35,5 +17,6 @@ public int compare(String s1, String s2) {
3517
while (!namePriorityQueue.isEmpty()) {
3618
System.out.println(namePriorityQueue.remove());
3719
}
20+
3821
}
3922
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import java.util.Comparator;
2+
import java.util.PriorityQueue;
3+
4+
public class PriorityQueueCustomComparatorExample {
5+
public static void main(String[] args) {
6+
Comparator<String> stringLengthComparator = new Comparator<String>() {
7+
@Override
8+
public int compare(String s1, String s2) {
9+
return s1.length() - s2.length();
10+
}
11+
};
12+
13+
/*
14+
The above Comparator can also be created using lambda expression like this =>
15+
Comparator<String> stringLengthComparator = (s1, s2) -> {
16+
return s1.length() - s2.length();
17+
};
18+
19+
The above statement can be shortened even further like this =>
20+
Comparator<String> stringLengthComparator = Comparator.comparingInt(String::length);
21+
*/
22+
23+
// Create a Priority Queue with a custom Comparator
24+
PriorityQueue<String> namePriorityQueue = new PriorityQueue<>(stringLengthComparator);
25+
26+
// Add items to a Priority Queue (ENQUEUE)
27+
namePriorityQueue.add("Lisa");
28+
namePriorityQueue.add("Robert");
29+
namePriorityQueue.add("John");
30+
namePriorityQueue.add("Chris");
31+
namePriorityQueue.add("Angelina");
32+
namePriorityQueue.add("Joe");
33+
34+
// Remove items from the Priority Queue (DEQUEUE)
35+
while (!namePriorityQueue.isEmpty()) {
36+
System.out.println(namePriorityQueue.remove());
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)