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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last