We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// Define the Student class
class Student {
private int id;
private String fname;
private double cgpa;
public Student(int id, String fname, double cgpa) {
this.id = id;
this.fname = fname;
this.cgpa = cgpa;
}
public int getId() {
return id;
}
public String getFname() {
return fname;
}
public double getCgpa() {
return cgpa;
}
}
// Implement the Comparator to sort the students
class SortByCGPA implements Comparator {
@Override
public int compare(Student s1, Student s2) {
// Compare CGPA first in decreasing order
if (s2.getCgpa() != s1.getCgpa()) {
return Double.compare(s2.getCgpa(), s1.getCgpa());
}
// If CGPA is same, compare by first name in alphabetical order
int nameComparison = s1.getFname().compareTo(s2.getFname());
if (nameComparison != 0) {
return nameComparison;
}
// If both CGPA and first name are the same, compare by ID in increasing order
return Integer.compare(s1.getId(), s2.getId());
}
}
// Main solution class
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
List<Student> studentList = new ArrayList<>();
// Input data
while (testCases > 0) {
int id = in.nextInt();
String fname = in.next();
double cgpa = in.nextDouble();
Student st = new Student(id, fname, cgpa);
studentList.add(st);
testCases--;
}
// Sort the list using the custom comparator
Collections.sort(studentList, new SortByCGPA());
// Output the first name of each student
for (Student st : studentList) {
System.out.println(st.getFname());
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Java Sort
You are viewing a single comment's thread. Return to all comments →
import java.util.*;
// Define the Student class class Student { private int id; private String fname; private double cgpa;
}
// Implement the Comparator to sort the students class SortByCGPA implements Comparator { @Override public int compare(Student s1, Student s2) { // Compare CGPA first in decreasing order if (s2.getCgpa() != s1.getCgpa()) { return Double.compare(s2.getCgpa(), s1.getCgpa()); }
}
// Main solution class public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int testCases = Integer.parseInt(in.nextLine());
}