HackerRank Java- Sort




You are given a list of student information: ID, FirstName, and CGPA. Your task is to rearrange them according to their CGPA in decreasing order. If two student have the same CGPA, then arrange them according to their first name in alphabetical order. If those two students also have the same first name, then order them according to their ID. No two students have the same ID.



  1. import java.util.*;
  2. class Student {
  3. private int id;
  4. private String fname;
  5. private double cgpa;
  6. public Student(int id, String fname, double cgpa) {
  7. super();
  8. this.id = id;
  9. this.fname = fname;
  10. this.cgpa = cgpa;
  11. }
  12. public int getId() {
  13. return id;
  14. }
  15. public String getFname() {
  16. return fname;
  17. }
  18. public double getCgpa() {
  19. return cgpa;
  20. }
  21. }
  22. public class Solution {
  23. public static void main(String[] args) {
  24. Scanner in = new Scanner(System.in);
  25. int testCases = Integer.parseInt(in.nextLine());
  26. List<Student> studentList = new ArrayList<Student>();
  27. while (testCases-- > 0) {
  28. int id = in.nextInt();
  29. String fname = in.next();
  30. double cgpa = in.nextDouble();
  31. Student st = new Student(id, fname, cgpa);
  32. studentList.add(st);
  33. }
  34. Collections.sort(studentList, Comparator.comparing(Student::getCgpa).reversed().
  35. thenComparing(Student::getFname).thenComparing(Student::getId));
  36. for (Student st : studentList) {
  37. System.out.println(st.getFname());
  38. }
  39. }
  40. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube