• + 18 comments

    Using Java 8

    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--;
          }
           
           Collections.sort(studentList,  Comparator.comparing(Student :: getCgpa).reversed().
                  thenComparing(Student :: getFname).thenComparing(Student :: getId));
          
             for(Student st: studentList){
             System.out.println(st.getFname());
          }
       }
    }
    
    • + 2 comments

      java8 rules

      • + 1 comment

        here is Java Sort problem solution https://programs.programmingoneonone.com/2021/02/hackerrank-java-sort-solution.html

        • + 0 comments

          Here are my few different solutions in Java. 100% all test cases will pass

          I hope you will find my answer useful.

          Hackerrank Java Sort Solution

      • + 0 comments

        updated solution is here

        https://www.thecscience.com/2021/05/HackerRank-java-sort-problem-solution.html

    • + 0 comments

      +1 for using Java 8 features.

      I think it's better to use the primitive specializations of Comparator.comparing() for primitive keys, that is comparingDouble() for the CGPA and comparingInt() for the ID. This way we can avoid unneccessary boxing.

      My next thaught: "Consider implementing Comparable" (check Joshua Bloch's "Effective Java")?

      Finally, using Java 8 we could even read the input data and generate a sorted list in one go:

      class Student implements Comparable<Student> {
        // ...
        private static final Comparator<Student> comp =
          Comparator.comparingDouble(Student::getCgpa).reversed()
                    .thenComparing(Student::getFname)
                    .thenComparingInt(Student::getId);
        // ...
        @Override
        public int compareTo(final Student other) {
          return comp.compare(this, other);
        }
      }
      
      public class Solution {
        public static void main(final String[] args) {
          final Scanner in = new Scanner(System.in);
          final int numTestCases = in.nextInt();
          in.nextLine();
          
          final List<Student> students = Stream.generate(() ->
              new Student(in.nextInt(),
                          in.next(),
                          in.nextDouble())
            ).limit(numTestCases).sorted().collect(toList());
              
          for (Student student : students) {
            System.out.println(student.getFname());
          }
        }
      }
      
    • + 1 comment

      Here is my solution:

      studentList.stream().sorted(Comparator.comparingDouble(Student::getCgpa).reversed().thenComparing(Comparator.comparing(Student::getFname)).thenComparing(Comparator.comparingInt(Student::getId))).map(Student::getFname).forEach(System.out::println);
      
      • + 2 comments

        what does that :: stands for in Student :: getCgpa

        • + 0 comments

          The double colon syntax is new to java 8 and lambdas. It points to functions and is equivalent to the alternative lambda -> expression

        • + 0 comments

          " :: " stands for Method Reference .It is most commonly used for instance methods of a class.As you might have observed ,unless you have something like this: d -> d.getCgpa()>10 in filter operations ,in all other(most commonly) operations viz sorted,map etc. you can use :: like:

          .map(Dish::getCalories) . A wonderful example would be for forEach : .forEach(System.out::println) !!

    • + 1 comment

      Comparator.comparing basically takes place of overriding the compareTo method, correct?

      • + 0 comments

        Kind of, yes. To be more precise:

        Comparator.comparing creates a Comparator, which can be used to sort a collection or stream. If you don't provide a Comparator to the sorting method, it will rely on the natural ordering of the elements of the collection instead. A natural ordering is given only when the element class does implement the Comparable interface and in this case the ordering is defined by overriding the compareTo method.

        So, yes it does - basically.

    • + 1 comment

      Hi, Comparator.comparing(Student :: getCgpa).reversed().

      Why are you using reversed() for only Cgpa comparison?

      • + 0 comments

        In java number are, by default, sorted ascending order ( from smal to big). when whe say reverse, we want the sorting to be descending (from big to smal)

    • + 0 comments

      How to do the same thing in Java 7? It is showing some erros in java 7

    • + 1 comment
         Collections.sort(studentList,  Comparator.comparing(Student :: getCgpa).reversed().
      
               what is the use of reveresed here???
      
      • + 0 comments

        It sorts in decreasing order the output we get from Collections.sort(studentList, Comparator.comparing(Student :: getCgpa) .As you might see ' comparing ' does bydefault increasing order sorting

    • + 1 comment

      May as well go all the way and use a stream

      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 LinkedList<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--;
      		}
              studentList.stream().sorted(
                  Comparator.comparing(Student::getCgpa).reversed()
                  .thenComparing(Student::getFname)
                  .thenComparing(Student::getId))
                  .map(Student::getFname).forEach(System.out::println);
      	}
      
      • + 0 comments

        why you have used testCases--;

    • + 0 comments

      Issue solved..really silly from my end!!!

    • + 0 comments

      Amazing

    • + 0 comments

      I implemented in a basic way.

          Comparator<Student> com=new Comparator<Student>()
          {
              public int compare(Student s1, Student s2){
                  if(s1.getCgpa()>s2.getCgpa())
                      return -1;
                  else if(s1.getCgpa()<s2.getCgpa())
                      return 1;
                  else{
                      if(s1.getFname().compareTo(s2.getFname())>0)
                          return 1;
                      else
                          return -1 ;   
                  }        
              }
          };
      
          Collections.sort(studentList, com);
      
    • + 0 comments

      int testCases = Integer.parseInt(in.nextLine());

        List<Student> studentList = new ArrayList<Student>();
      
              i am not getting this 
      
    • + 0 comments

      Can you explain this solution Collection.sort() line

    • + 0 comments

      instead of while loop if i try for loop i got wrong answer. can anyone help me to write for loop for program.

    • [deleted]
      + 0 comments

      Nice - but how would you write unit tests that exercise all the combinations of the sorting? Making the Student class Comparable, or at least having a separate Comparator, would help greatly with testing.

    • + 0 comments

      This solution shows wrong answer.

    • + 1 comment
      [deleted]
    • + 0 comments

      It makes compilation error as I tried. It seems that this code has no syntax error, maybe hackerrank system has a problem.