|
| 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