exp 3.1 java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment.:3.1

Student Name:SACHIN KUMAR SACHAN UID:21BCS9802


Branch: CSE Section/Group: 905/A
rd
Semester: 3 Date of Performance:27/10/2022
Subject Name: OBJECT ORIENTED Subject Code:21CSH-218
PROGRAMMING USING JAVA

Aim of the practical:


Hackerrank problem related to java sort.

Objective:

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 theoracledocsto learn about
comparators.

Program Code:

import java.util.*;

class Student implements Comparable<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;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

}
public int getId()
{
return id;
}
public String getFname()
{
return fname;
}
public double getCgpa()
{
return cgpa;
}
public int compareTo(Student o)
{
if(this.cgpa!=o.cgpa)
{
if(this.cgpa>o.cgpa)
return -1;
else
return 1;
}
else if(this.fname.equals(o.fname))
{
return Integer.compare(this.id, o.id);
}
else
{
if(this.fname.compareTo(o.fname)<0)
return -1;
else
return 1;

}
}
}

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>();


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

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

Output:

Learning outcomes (What I have learnt):

1. I have learnt how to use comparators.

2. I have learnt how to use compareTo() function.

3. I have learnt how to sort a list by taking many pieces of information into consideration.

You might also like