Java PriorityQueue Challenge Solved with Custom Comparator

🚀 Solved: Java Priority Queue Challenge (HackerRank) Today I worked on an interesting problem involving PriorityQueue in Java, where students are served based on multiple priority conditions: 🎯 Priority Rules: ✔ Highest CGPA first ✔ If CGPA is same → Name in ascending order ✔ If both same → Lower ID first 💡 What I learned: 🔹 How to use Comparator with PriorityQueue 🔹 Handling multiple sorting conditions 🔹 Difference between writing code in Eclipse vs HackerRank 🔹 Importance of using the correct constructor: PriorityQueue<Student> pq = new PriorityQueue<>(1, new Comparator<Student>() { public int compare(Student s1, Student s2) { if (s1.getCGPA() != s2.getCGPA()) { return Double.compare(s2.getCGPA(), s1.getCGPA()); } else if (!s1.getName().equals(s2.getName())) { return s1.getName().compareTo(s2.getName()); } else { return s1.getID() - s2.getID(); } } }); ⚠️ Key Debugging Insight: I initially faced an error: 👉 “no suitable constructor found for PriorityQueue” ✔ The fix was to provide initial capacity along with Comparator, especially in platforms like HackerRank. 📌 Takeaway: PriorityQueue is powerful, but understanding custom ordering logic and environment differences is crucial. #Java #DataStructures #PriorityQueue #HackerRank #ProblemSolving #JavaDeveloper #CodingJourney #Learning

To view or add a comment, sign in

Explore content categories