Home  >  Core Java

Example of PriorityQueue in java

By Arvind Rai, December 09, 2012
java.util.PriorityQueue has been introduced in JDK 1.5. PriorityQueue maintains the element ordering on the basis of java Comparable and Comparator. When PriorityQueue orders the elements on the basis of Comparable implemented by element class, it is known as natural ordering and this is the PriorityQueue default ordering.

Using PriorityQueue methods

In our example below, see the use of PriorityQueue with the methods add(), poll() and remove() etc. add() method adds the element in PriorityQueue. poll() method fetches the element from head and removes it. remove() method removes the specified element.
PriorityQueueTest.java
package com.concretepage;
import java.util.PriorityQueue;
public class PriorityQueueTest {
	public static void main(String... args ){
		PriorityQueue<String> pq=new PriorityQueue<String>();
		pq.add("A");
		pq.add("B");
		pq.add("C");
		pq.add("D");
		System.out.println("After Using add method.");
		for(String s:pq){ 
			System.out.println(s);
		}
		System.out.println("After Using poll method.");
		pq.poll();
		for(String s:pq){ 
			System.out.println(s);
		}
		System.out.println("After Using remove method.");
		pq.remove("D");
		for(String s:pq){ 
			System.out.println(s);
		}
	}
}

Using Comparator in PriorityQueue

PriorityQueue can also be used with java Comparator. PriorityQueue provides a constructor that takes the initial size and Comparator object. It sorts then according to logic implemented in Comparator.
PriorityQueueTest.java
package com.concretepage;
import java.util.Comparator;
import java.util.PriorityQueue;
public class PriorityQueueTest {
	public static void main(String... args ){
		PriorityQueueComparator pqc=new PriorityQueueComparator();
		PriorityQueue<String> pq=new PriorityQueue<String>(5,pqc);
		pq.add("ABC");
		pq.add("BD");
		pq.add("ABCD");
		for(String s:pq){ 
			System.out.println(s);
		}
	}
}
class PriorityQueueComparator implements Comparator<String>{
	public int compare(String s1, String s2) {
        if (s1.length() < s2.length()) {
            return -1;
        }
        if (s1.length() > s2.length()) {
            return 1;
        }
        return 0;
    }
}
Find the output.
BD
ABC
ABCD
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us