Skip to main content

Java Sort Hackerrank Solution | Comparator with Three Properties

Sort Java List using Comparator Interface for Three Object Values

Java Sort Hackerrank Solution | Sort list using comparator for three values

Problem Description :-

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.

Hint: You can use comparators to sort a list of objects. See the oracle docs to learn about comparators.

Input Format

The first line of input contains an integer N, representing the total number of students. The next N lines contains a list of student information in the following structure:

    ID  Name CGPA

Read full description on HackerRank :-

Solution 1 :- Sort Java list using Inner class (Comparator) with Three Object properties

In this problem we are using Comparator Interface. Comparator Interface is used to order objects inside a user-defined class (POJO - Plain Old Java Object).

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, new Comparator<Student>() {

            @Override
            public int compare(Student o1, Student o2) {
                if (o1.getCgpa() == o2.getCgpa() && o1.getFname().equals(o2.getFname())) {
                    return o2.getId() - o1.getId();
                } else if (o1.getCgpa() == o2.getCgpa()) {
                    return o1.getFname().compareTo(o2.getFname());
                } else {
                    return o1.getCgpa() > o2.getCgpa() ? -1 : 1;
                }
            }
        });

      
          for(Student st: studentList){
            System.out.println(st.getFname());
        }
    }
}

Input and Output :-

Input

5
33 Rumpa 3.68
85 Ashis 3.85
56 Samiha 3.75
19 Samara 3.75
22 Fahim 3.76 

Output

Ashis
Fahim
Samara
Samiha
Rumpa

Explanation :-

  • We are using Collections.sort() for sorting our list. In sort() method we are passing two arguments.
    1. list (which we want to sort).
    2. Comparator (comparator to determine the order of the list).
  • We are creating inner comparator class, and we must have to implement compare() method.
  • In compare() method we are passing two parameters, that is Student object.
  • In first if condition, we are checking if both CGPA and first name are same then we are sorting based on Student id.
  • If CGPA are same, then sort based on first name.
  • Otherwise sort based on CGPA only.

We can also implement Comparator interface in Student or Solution class.So lets see how we can implement Comparable in Student class and achieve Sorting.

Learn more about Comparator Interface in Java.

Solution 2 :-  Sort Java list using implementing Comparator Interface

import java.util.*;

class Student implements Comparator<Student> {
    private int id;
    private String fname;
    private double cgpa;
    
    public Student() {
        // TODO Auto-generated constructor stub
    }

    
    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;
    }
    
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.getCgpa() == o2.getCgpa() && o1.getFname().equals(o2.getFname())) {
            return o2.getId() - o1.getId();
        } else if (o1.getCgpa() == o2.getCgpa()) {
            return o1.getFname().compareTo(o2.getFname());
        } else {
            return o1.getCgpa() > o2.getCgpa() ? -1 : 1;
        }
    }

}

//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, new Student());
      
        for(Student st: studentList){
            System.out.println(st.getFname());
        }
    }
}

Java Comparator interface compare method

Explanation :-

  • First we are implements Comparable in Student class. If we implement Comparable, then we must to implement compare() method in Student class. (Refer above image)
  • We are same logic as above solution in compare() method.
  • In Solution class we are pass Two parameters : Student list and new Student Object in Collections.sort() method.
  • You can refer Bold code for as new updated in above solution.

We can also use Java 8 for better and clean code. refer below solution for java 8 code.

Solution 3 :- Sort Java list using Java 8

Collections.sort(studentList,  
        Comparator.comparing(Student :: getCgpa).reversed()
        .thenComparing(Student :: getFname)
        .thenComparing(Student :: getId));

 

Comments

Popular posts from this blog

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...