The provided Java code is a solution to a problem where a list of students needs to be sorted. Each student has an ID, a name, and a CGPA. The sorting should be done primarily by CGPA in descending order, then by name in alphabetical order, and finally by ID in ascending order.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution approach is to use a custom comparator with the Collections.sort() method. The comparator first compares the CGPA of two students. If the CGPA is the same, it compares the names. If the names are also the same, it compares the IDs. This ensures that the list of students is sorted as per the required conditions. The sorted list of students is then printed to the console.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.datastructures;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
/**
*
*/
class Student {
private int id;
private String fname;
private double cgpa;
public Student(int id, String fname, double cgpa) {
super();
this.id = id;
this.fname = fname;
this.cgpa = cgpa;
}
public int getId() {
return id;
}
public String getFname() {
return fname;
}
public double getCgpa() {
return cgpa;
}
}
// Complete the code
public class JavaSort {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
List studentList = new ArrayList();
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--;
}
Collections.sort(studentList, new Comparator() {
public int compare(Student s1, Student s2) {
if (s1.getCgpa() == s2.getCgpa()) {
if (s1.getFname().equals(s2.getFname())) {
return s1.getId() - s2.getId();
} else {
return s1.getFname().compareTo(s2.getFname());
}
} else {
return (int) (s2.getCgpa() * 1000 - s1.getCgpa() * 1000);
}
}
});
for (Student st : studentList) {
System.out.println(st.getFname());
}
in.close();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.