11.) Priority Queue(basics)

 Write a programe to find second smallest element of a  Priority Queue.(its just like find kth element from the queue (second smallest element) its just for confusion cuz its a  Priority Queue.)

import java.util.PriorityQueue;

public class RemovePriorityQueueElements {
   public static int small( PriorityQueue<Integer> pq,int k) {
     
     
      if(k>pq.size()){
        System.out.println("invalid");
          return -1;
      }

          for(int i=0;i<=k-1;i++){
            pq.remove();
           
          }
         
            return pq.peek();
       
         
     
    }

    public static void main(String[] args) {

        // Creating a priority queue
      PriorityQueue<Integer> pq = new PriorityQueue<>();
     
      // Adding elements to the priority queue
      pq.add(10);
      pq.add(20);
      pq.add(15);
      pq.add(30);
      pq.add(25);
     
      // Printing the original priority queue
      System.out.println("Original Priority Queue: " + pq);

     
        int k=3;
        int c=small(pq ,k);
        System.out.println(c);
    }
}

Comments