record Student(int id,
String name, double cgpa) implements Comparable<Student>
{
@Override
public int compareTo(Student other) {
// Compare CGPA in
descending order
return switch (Double.compare(other.cgpa, this.cgpa)) {
case 0 -> // If
CGPAs are equal, compare names
switch (this.name.compareTo(other.name)) {
case
0 -> // If names are equal, compare IDs
Integer.compare(this.id, other.id);
default
-> this.name.compareTo(other.name);
};
default -> Double.compare(other.cgpa, this.cgpa);
};
}
}
class Student implements Comparable<Student>
{
int id;
String name;
double cgpa;
@Override
public int compareTo(Student other) {
if (this.cgpa != other.cgpa) {
return Double.compare(other.cgpa, this.cgpa); // descending
}
if (!this.name.equals(other.name)) {
return this.name.compareTo(other.name); //
ascending
}
return Integer.compare(this.id, other.id); // ascending
}
}
alternative
public class StudentGrade {
// Student record using
Java 16+ record feature
public record Student(int id, String name, double cgpa)
{}
public static void main(String[] args) {
List<String> events = List.of(
"ENTER
John 3.75 50",
"ENTER
Mark 3.8 24",
"ENTER
Shafaet 3.7 35",
"SERVED",
"SERVED",
"ENTER
Samiha 3.85 36",
"SERVED",
"ENTER
Ashley 3.9 42",
"ENTER
Maria 3.6 46",
"ENTER
Anik 3.95 49",
"ENTER
Dan 3.95 50",
"SERVED"
);
Priorities p = new Priorities();
List<Student> students = p.getStudents(events);
students.forEach(System.out::println);
}
public static class Priorities {
public List<Student> getStudents(List<String> events) {
Comparator<Student> studentComparator = Comparator
.comparingDouble(Student::cgpa).reversed()
.thenComparing(Student::name)
.thenComparingInt(Student::id);
PriorityQueue<Student> pq = new PriorityQueue<>(studentComparator);
for (String event : events) {
if (event.startsWith("ENTER")) {
String[] parts = event.split("\\s+");
String name = parts[1];
double cgpa = Double.parseDouble(parts[2]);
int id = Integer.parseInt(parts[3]);
pq.offer(new
Student(id, name, cgpa));
} else if (event.equals("SERVED")) {
pq.poll();
}
}
return pq.stream().toList();
}
}
}
·
reeSet does not
allow duplicate elements. If you try to add an element
that compares as equal to an existing one, it will not be added.
·
PriorityQueue allows
duplicates.