diff --git a/java-priority-queue-examples b/java-priority-queue-examples new file mode 100644 index 0000000..c976688 --- /dev/null +++ b/java-priority-queue-examples @@ -0,0 +1,87 @@ +import java.util.PriorityQueue; + +public class CreatePriorityQueueExample { + public static void main(String[] args) { + // Create a Priority Queue + PriorityQueue numbers = new PriorityQueue<>(); + + // Add items to a Priority Queue (ENQUEUE) + numbers.add(750); + numbers.add(500); + numbers.add(900); + numbers.add(100); + + // Remove items from the Priority Queue (DEQUEUE) + while (!numbers.isEmpty()) { + System.out.println(numbers.remove()); + } + + } +} + +************************************************************************************************************************************************************************** + +import java.util.PriorityQueue; + +public class CreatePriorityQueueStringExample { + public static void main(String[] args) { + // Create a Priority Queue + PriorityQueue namePriorityQueue = new PriorityQueue<>(); + + // Add items to a Priority Queue (ENQUEUE) + namePriorityQueue.add("Lisa"); + namePriorityQueue.add("Robert"); + namePriorityQueue.add("John"); + namePriorityQueue.add("Chris"); + namePriorityQueue.add("Angelina"); + namePriorityQueue.add("Joe"); + + // Remove items from the Priority Queue (DEQUEUE) + while (!namePriorityQueue.isEmpty()) { + System.out.println(namePriorityQueue.remove()); + } + + } +} + +************************************************************************************************************************************************************************ + +import java.util.Comparator; +import java.util.PriorityQueue; + +public class PriorityQueueCustomComparatorExample { + public static void main(String[] args) { + Comparator stringLengthComparator = new Comparator() { + @Override + public int compare(String s1, String s2) { + return s1.length() - s2.length(); + } + }; + + /* + The above Comparator can also be created using lambda expression like this => + Comparator stringLengthComparator = (s1, s2) -> { + return s1.length() - s2.length(); + }; + + The above statement can be shortened even further like this => + Comparator stringLengthComparator = Comparator.comparingInt(String::length); + */ + + // Create a Priority Queue with a custom Comparator + PriorityQueue namePriorityQueue = new PriorityQueue<>(stringLengthComparator); + + // Add items to a Priority Queue (ENQUEUE) + namePriorityQueue.add("Lisa"); + namePriorityQueue.add("Robert"); + namePriorityQueue.add("John"); + namePriorityQueue.add("Chris"); + namePriorityQueue.add("Angelina"); + namePriorityQueue.add("Joe"); + + // Remove items from the Priority Queue (DEQUEUE) + while (!namePriorityQueue.isEmpty()) { + System.out.println(namePriorityQueue.remove()); + } + } +}