Java PriorityQueue: add() and size() methods
KW.java
import java.util.PriorityQueue;

class KW 
{
    public static void main(String[] args) 
    {
        //PriorityQueue class implements the Queue interface
        PriorityQueue<String> pq=new PriorityQueue<>();
        pq.add("Apple");
        pq.add("Orange");
        pq.add("Mango");
        pq.add("Grapes");
        pq.add("Cherry");
        pq.add("Apple");
        pq.add("Blueberry");
        System.out.println(pq);
        System.out.println("Size: "+pq.size());
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW [Apple, Cherry, Apple, Orange, Grapes, Mango, Blueberry] Size: 7 kodingwindow@kw:~$
Java PriorityQueue: peek() and poll() methods
KW.java
import java.util.PriorityQueue;

class KW 
{
    public static void main(String[] args) 
    {
        //PriorityQueue class implements the Queue interface
        PriorityQueue<String> pq=new PriorityQueue<>();
        pq.add("Apple");
        pq.add("Orange");
        pq.add("Mango");
        pq.add("Grapes");
        pq.add("Cherry");
        pq.add("Apple");
        pq.add("Blueberry");
        System.out.println(pq);
        System.out.println("Head element: "+pq.element());
        
        pq.poll();
        System.out.println("\n"+pq);
        System.out.println("Peek element: "+pq.peek());
        
        pq.remove();
        System.out.println("\n"+pq);
        System.out.println("Peek element: "+pq.peek());
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW [Apple, Cherry, Apple, Orange, Grapes, Mango, Blueberry] Head element: Apple [Apple, Cherry, Blueberry, Orange, Grapes, Mango] Peek element: Apple [Blueberry, Cherry, Mango, Orange, Grapes] Peek element: Blueberry kodingwindow@kw:~$
Advertisement