JAVA SORT HACKKERANK WITH COMPARATOR.COMPARING AND THEN COMPARING FUNCTION
import java.util.*;
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 Solution
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
List<Student> studentList = new ArrayList<Student>();
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--;
}/*
Comparator<Student> compareByCgpa = (Student o1, Student o2) ->
(int)(o1.getCgpa()-o2.getCgpa());
Collections.sort(studentList, compareByCgpa.reversed());
for(int i=0;i<studentList.size()-1;i++){
if((studentList.get(i)).getCgpa()==(studentList.get(i+1)).getCgpa()){
if(String.valueOf(studentList.get(i).getFname()).
compareTo(String.valueOf(studentList.get(i+1) .getFname()))>0){
String temp1=String.valueOf(studentList.get(i).getFname());
String temp2=String.valueOf(studentList.get(i+1).getFname());
String temp3;
temp3=temp1;
temp1=temp2;
temp2=temp3;
}
else if(String.valueOf(studentList.get(i).getFname()).
compareTo(String.valueOf(studentList.get(i+1).getFname()))==0){
if((studentList.get(i).getId()-studentList.get(i+1).getId())>0){
int temp1=studentList.get(i).getId();
int temp2=studentList.get(i+1).getId();;
int temp3;
temp3=temp1;
temp1=temp2;
temp2=temp3;
}
}
}
}
*/
Collections.sort(studentList, Comparator.comparing(Student :: getCgpa).reversed().thenComparing(Student :: getFname).thenComparing(Student :: getId));
for(Student st: studentList){
System.out.println(st.getFname());
}
}
}
Comments
Post a Comment