{"id":1263,"date":"2022-02-26T07:08:00","date_gmt":"2022-02-26T07:08:00","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1263"},"modified":"2022-02-26T07:08:00","modified_gmt":"2022-02-26T07:08:00","slug":"priority-queue","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/26\/priority-queue\/","title":{"rendered":"Priority Queue"},"content":{"rendered":"\n<p>In this tutorial, we will learn about the PriorityQueue class of the Java collections framework with the help of examples.<\/p>\n\n\n\n<p>The\u00a0<code>PriorityQueue<\/code>\u00a0class provides the functionality of the\u00a0heap data structure.<\/p>\n\n\n\n<p>It implements the\u00a0Queue interface.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/cdn.programiz.com\/sites\/tutorial2program\/files\/java-priorityqueue-implementation.png\" alt=\"The Java PriorityQueue class implements the Queue interface.\"\/><\/figure>\n\n\n\n<p>Unlike normal queues, priority queue elements are retrieved in sorted order.<\/p>\n\n\n\n<p>Suppose, we want to retrieve elements in the ascending order. In this case, the head of the priority queue will be the smallest element. Once this element is retrieved, the next smallest element will be the head of the queue.<\/p>\n\n\n\n<p>It is important to note that the elements of a priority queue may not be sorted. However, elements are always retrieved in sorted order.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"create\">Creating PriorityQueue<\/h2>\n\n\n\n<p>In order to create a priority queue, we must import the&nbsp;<code>java.util.PriorityQueue<\/code>&nbsp;package. Once we import the package, here is how we can create a priority queue in Java.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>PriorityQueue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;();\n<\/code><\/pre>\n\n\n\n<p>Here, we have created a priority queue without any arguments. In this case, the head of the priority queue is the smallest element of the queue. And elements are removed in ascending order from the queue.<\/p>\n\n\n\n<p>However, we can customize the ordering of elements with the help of the&nbsp;<code>Comparator<\/code>&nbsp;interface. We will learn about that later in this tutorial.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Methods of PriorityQueue<\/h2>\n\n\n\n<p>The&nbsp;<code>PriorityQueue<\/code>&nbsp;class provides the implementation of all the methods present in the&nbsp;<code>Queue<\/code>&nbsp;interface.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"insert\">Insert Elements to PriorityQueue<\/h2>\n\n\n\n<ul><li><code>add()<\/code>&nbsp;&#8211; Inserts the specified element to the queue. If the queue is full, it throws an exception.<\/li><li><code>offer()<\/code>&nbsp;&#8211; Inserts the specified element to the queue. If the queue is full, it returns&nbsp;<code>false<\/code>.<\/li><\/ul>\n\n\n\n<p>For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.PriorityQueue;\n\nclass Main {\n    public static void main(String&#91;] args) {\n\n        \/\/ Creating a priority queue\n        PriorityQueue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;();\n\n        \/\/ Using the add() method\n        numbers.add(4);\n        numbers.add(2);\n        System.out.println(\"PriorityQueue: \" + numbers);\n\n        \/\/ Using the offer() method\n        numbers.offer(1);\n        System.out.println(\"Updated PriorityQueue: \" + numbers);\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>PriorityQueue: &#91;2, 4]\nUpdated PriorityQueue: &#91;1, 4, 2]\n<\/samp><\/code><\/pre>\n\n\n\n<p>Here, we have created a priority queue named&nbsp;<var>numbers<\/var>. We have inserted 4 and 2 to the queue.<\/p>\n\n\n\n<p>Although 4 is inserted before 2, the head of the queue is 2. It is because the head of the priority queue is the smallest element of the queue.<\/p>\n\n\n\n<p>We have then inserted 1 to the queue. The queue is now rearranged to store the smallest element 1 to the head of the queue.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"acess\">Access PriorityQueue Elements<\/h2>\n\n\n\n<p>To access elements from a priority queue, we can use the&nbsp;<code>peek()<\/code>&nbsp;method. This method returns the head of the queue. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.PriorityQueue;\n\nclass Main {\n    public static void main(String&#91;] args) {\n\n        \/\/ Creating a priority queue\n        PriorityQueue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;();\n        numbers.add(4);\n        numbers.add(2);\n        numbers.add(1);\n        System.out.println(\"PriorityQueue: \" + numbers);\n\n        \/\/ Using the peek() method\n        int number = numbers.peek();\n        System.out.println(\"Accessed Element: \" + number);\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>PriorityQueue: &#91;1, 4, 2]\nAccessed Element: 1\n<\/samp><\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"remove\">Remove PriorityQueue Elements<\/h2>\n\n\n\n<ul><li><code>remove()<\/code>&nbsp;&#8211; removes the specified element from the queue<\/li><li><code>poll()<\/code>&nbsp;&#8211; returns and removes the head of the queue<\/li><\/ul>\n\n\n\n<p>For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.PriorityQueue;\n\nclass Main {\n    public static void main(String&#91;] args) {\n\n        \/\/ Creating a priority queue\n        PriorityQueue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;();\n        numbers.add(4);\n        numbers.add(2);\n        numbers.add(1);\n        System.out.println(\"PriorityQueue: \" + numbers);\n\n        \/\/ Using the remove() method\n        boolean result = numbers.remove(2);\n        System.out.println(\"Is the element 2 removed? \" + result);\n\n        \/\/ Using the poll() method\n        int number = numbers.poll();\n        System.out.println(\"Removed Element Using poll(): \" + number);\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>PriorityQueue: &#91;1, 4, 2]\nIs the element 2 removed? true\nRemoved Element Using poll(): 1\n<\/samp><\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"iterate\">Iterating Over a PriorityQueue<\/h2>\n\n\n\n<p>To iterate over the elements of a priority queue, we can use the&nbsp;<code>iterator()<\/code>&nbsp;method. In order to use this method, we must import the&nbsp;<code>java.util.Iterator<\/code>&nbsp;package. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.PriorityQueue;\nimport java.util.Iterator;\n\nclass Main {\n    public static void main(String&#91;] args) {\n\n        \/\/ Creating a priority queue\n        PriorityQueue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;();\n        numbers.add(4);\n        numbers.add(2);\n        numbers.add(1);\n        System.out.print(\"PriorityQueue using iterator(): \");\n\n        \/\/Using the iterator() method\n        Iterator&lt;Integer&gt; iterate = numbers.iterator();\n        while(iterate.hasNext()) {\n            System.out.print(iterate.next());\n            System.out.print(\", \");\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>PriorityQueue using iterator(): 1, 4, 2,\n<\/samp><\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Other PriorityQueue Methods<\/h2>\n\n\n\n<figure class=\"wp-block-table is-style-regular\"><table><tbody><tr><th>Methods<\/th><th>Descriptions<\/th><\/tr><tr><td><code>contains(element)<\/code><\/td><td>Searches the priority queue for the specified element. If the element is found, it returns <code>true<\/code>, if not it returns <code>false<\/code>.<\/td><\/tr><tr><td><code>size()<\/code><\/td><td>Returns the length of the priority queue.<\/td><\/tr><tr><td><code>toArray()<\/code><\/td><td>Converts a priority queue to an array and returns it.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"comparator\">PriorityQueue Comparator<\/h2>\n\n\n\n<p>In all the examples above, priority queue elements are retrieved in the natural order (ascending order). However, we can customize this ordering.<\/p>\n\n\n\n<p>For this, we need to create our own comparator class that implements the&nbsp;<code>Comparator<\/code>&nbsp;interface. For example,<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.util.PriorityQueue;\nimport java.util.Comparator;\nclass Main {\n    public static void main(String&#91;] args) {\n\n        \/\/ Creating a priority queue\n        PriorityQueue&lt;Integer&gt; numbers = new PriorityQueue&lt;&gt;(new CustomComparator());\n        numbers.add(4);\n        numbers.add(2);\n        numbers.add(1);\n        numbers.add(3);\n        System.out.print(\"PriorityQueue: \" + numbers);\n    }\n}\n\nclass CustomComparator implements Comparator&lt;Integer&gt; {\n\n    @Override\n    public int compare(Integer number1, Integer number2) {\n        int value =  number1.compareTo(number2);\n        \/\/ elements are sorted in reverse order\n        if (value &gt; 0) {\n            return -1;\n        }\n        else if (value &lt; 0) {\n            return 1;\n        }\n        else {\n            return 0;\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><samp>PriorityQueue: &#91;4, 3, 1, 2]\n<\/samp><\/code><\/pre>\n\n\n\n<p>In the above example, we have created a priority queue passing&nbsp;<var>CustomComparator<\/var>&nbsp;class as an argument.<\/p>\n\n\n\n<p>The&nbsp;<var>CustomComparator<\/var>&nbsp;class implements the&nbsp;<code>Comparator<\/code>&nbsp;interface.<\/p>\n\n\n\n<p>We then override the&nbsp;<code>compare()<\/code>&nbsp;method. The method now causes the head of the element to be the largest number.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will learn about the PriorityQueue class of the Java collections framework with the help of examples. The\u00a0PriorityQueue\u00a0class provides the functionality of the\u00a0heap data structure. It implements the\u00a0Queue interface. Unlike normal queues, priority queue elements are retrieved in sorted order. Suppose, we want to retrieve elements in the ascending order. In this [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[291],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1263"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1263"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1263\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1263"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1263"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1263"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}