Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
How to Customize the Ordering of Elements in a PriorityQueue Using a Comparator in Java?
Next article icon

How to Customize the Ordering of Elements in a PriorityQueue Using a Comparator in Java?

Last Updated : 15 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A PriorityQueue is a data structure that allows elements to be processed based on their priority. By default, it orders elements according to their natural ordering (e.g., numeric values in ascending order). However, sometimes we need a different sorting order based on specific criteria.

In this article, we will learn to Customize the Ordering of Elements in a PriorityQueue Using a Comparator in Java.

Prerequisites:

  • Java Collections Framework
  • Comparator vs Comparable.

Customize the Ordering of Elements in a PriorityQueue

Using a Custom Comparator to customize the ordering of elements in a PriorityQueue, follow these steps:

  • When constructing a PriorityQueue, provide a custom comparator a define the desired order.
  • The constructor PriorityQueue (int capacity, Comparator<E> comparator) allows you to create a PriorityQueue with a specified initial capacity and a custom comparator.
  • The comparator determines how elements are compared and ordered.

Program to Customize the Ordering of Elements in a PriorityQueue

Let's create a PriorityQueue of students based on their CGPA (grade point average). We'll define a custom comparator (StudentComparator) that compares students' CGPA values

Below is the implementation of Customize the Ordering of Elements in a PriorityQueue:

Java
// Java Program to Customize the Ordering // of Elements in a PriorityQueue import java.util.*;  // Class representing a priority queue of students public class GFG {     // Main method     public static void main(String[] args) {         // Create a scanner object for input         Scanner in = new Scanner(System.in);                  // Create a priority queue of students with custom comparator         PriorityQueue<Student> pq = new PriorityQueue<>(5, new StudentComparator());          // Create student objects and add them to the priority queue         Student student1 = new Student("Nandini", 3.2);         pq.add(student1);          Student student2 = new Student("Anmol", 3.6);         pq.add(student2);          Student student3 = new Student("Palak", 4.0);         pq.add(student3);          // Print the students served in their priority order         System.out.println("Students served in their priority order:");         while (!pq.isEmpty()) {             System.out.println(pq.poll().getName());         }     } }  // Comparator class for comparing students based on their CGPA class StudentComparator implements Comparator<Student> {     // Compare method to compare two students     public int compare(Student s1, Student s2) {         if (s1.cgpa < s2.cgpa) return 1;         else if (s1.cgpa > s2.cgpa) return -1;         return 0;     } }  // Class representing a student class Student {     // Member variables     public String name;     public double cgpa;      // Constructor     public Student(String name, double cgpa) {         this.name = name;         this.cgpa = cgpa;     }      // Method to get the name of the student     public String getName() {         return name;     } } 

Output
Students served in their priority order:  Palak  Anmol  Nandini      

Explanation of the above Program:

  • In the example above, we create a priorityQueue of Students.
  • The custom comparator (StudentComparator) orders students based on their CGPA.
  • Students with higher CGPA are served first, demonstrating customized ordering.

Let's explore another approach for customizing the ordering of elements in a PriorityQueue using a Comparator in java.

Ordering Strings by Length

Suppose we want to create a PriorityQueue that orders strings based on their length (number of characters). we'll define a custom comparator to achieve this.Create a new Java file (e.g., StringLengthPriorityQueue.java)

Below is the implementation of Ordering Strings by Length:

Java
// Java Program to Customize the Ordering // of Elements in a PriorityQueue import java.util.*;  // Class representing a priority queue based on string length public class StringLengthPriorityQueue {     // Main method     public static void main(String[] args) {         // Create a priority queue of strings with custom comparator         PriorityQueue<String> pq = new PriorityQueue<>(5, new StringLengthComparator());          // Add strings to the priority queue         pq.add("apple");         pq.add("banana");         pq.add("grape");         pq.add("kiwi");          // Print the strings served in order of length         System.out.println("Strings served in order of length:");         while (!pq.isEmpty()) {             System.out.println(pq.poll());         }     } }  // Comparator class for comparing strings based on their length class StringLengthComparator implements Comparator<String> {     // Compare method to compare two strings based on their length     public int compare(String s1, String s2) {         return Integer.compare(s1.length(), s2.length());     } } 

Output
Strings served in order of length:  kiwi  apple  grape  banana      

Explanation of the above Program:

  • In this example, we create a PriorityQueue of Strings.
  • The custom comparator ( StringLengthComparator ) compares strings based on their length.
  • Strings with shorter lengths are served first.

Next Article
How to Customize the Ordering of Elements in a PriorityQueue Using a Comparator in Java?

J

javvajisunil16
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-Collections
  • priority-queue
  • java-priority-queue
  • Java Examples
Practice Tags :
  • Java
  • Java-Collections
  • priority-queue

Similar Reads

    Custom Comparator for a Specific Element type in a PriorityQueue in Java
    PriorityQueue in Java is a data structure that stores elements according to their specified natural order or comparison. By default, it uses a natural order, but we can also define customized comparisons to sort things out based on specific criteria. Custom Comparator in PriorityQueueA Custom Compar
    3 min read
    How to Iterate over the Elements of a PriorityQueue in Java?
    In Java, a Priority Queue is a Data structure that allows the users to store data based on their priority so that the elements with the highest priority can be accessed in constant time. In this article, we will learn how to iterate over the elements of a PriorityQueue in Java. Example Input: Priori
    2 min read
    How to Copy Elements from One PriorityQueue to Another in Java?
    In Java, a priority queue is a data structure that allows the users to store data based on their priority. In this article, we will learn how to copy elements from one priority queue to another in Java. Example Input: PriorityQueue original ={1,2,3,4,5}Output: PriorityQueue Copy ={1,2,3,4,5}Copy ele
    2 min read
    How to Check if a PriorityQueue is Empty or Contains Elements in Java?
    In this article, we will demonstrate how to check if a Priority Queue is empty or not. The java.util.PriorityQueue.isEmpty() method is used to check if the Priority Queue is empty or not. Based on the Boolean value it returns the Response for the same. Syntax: Priority_Queue.isEmpty()Parameters: The
    2 min read
    How to Sort TreeSet Elements using Comparable Interface in Java?
    TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a Set using their natural ordering whether an explicit comparator is provided. To sort TreeSet elements using Comparable interface in java first, we create a cl
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences