![]() |
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:Customize the Ordering of Elements in a PriorityQueueUsing a Custom Comparator to customize the ordering of elements in a PriorityQueue, follow these steps:
Program to Customize the Ordering of Elements in a PriorityQueueLet’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
Output
Students served in their priority order: Palak Anmol Nandini Explanation of the above Program:
Let’s explore another approach for customizing the ordering of elements in a PriorityQueue using a Comparator in java. Ordering Strings by LengthSuppose 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
Output
Strings served in order of length: kiwi apple grape banana Explanation of the above Program:
|
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |