w3resource

Java: Insert a given element into a priority queue


4. Insert Element into PriorityQueue

Write a Java program to insert a given element into a priority queue.

Sample Solution:-

Java Code:

import java.util.PriorityQueue;

  public class Example4 {
  public static void main(String[] args) {

   // Create Priority Queue
           PriorityQueue<String> pq1 = new PriorityQueue<String>();  
   // use add() method to add values in the Priority Queue
          pq1.add("Red");
          pq1.add("Green");
          pq1.add("Black");
          pq1.add("White");
    System.out.println("Original Priority Queue: "+pq1);
   
   // Inserts the specified element into this priority queue.
    pq1.offer("Blue");
 
    System.out.println("The New Priority Queue: " + pq1);
  } 
}

Sample Output:

Original Priority Queue: [Black, Red, Green, White]                    
The New Priority Queue: [Black, Blue, Green, White, Red]

For more Practice: Solve these Related Problems:

  • Write a Java program to insert an element into a PriorityQueue using offer() and then print the head element to verify its position.
  • Write a Java program to insert a new element into a PriorityQueue with a custom comparator and display the updated ordering.
  • Write a Java program to conditionally insert an element into a PriorityQueue only if it is not already present, then print the queue.
  • Write a Java program to implement a method that inserts multiple elements into a PriorityQueue and then prints the queue after each insertion.

Go to:


PREV : Add All Elements to Another PriorityQueue.
NEXT : Clear PriorityQueue.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.