-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComparator2.java
More file actions
82 lines (72 loc) · 2.56 KB
/
Comparator2.java
File metadata and controls
82 lines (72 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*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.
The name contains only lowercase English letters. The contains only integer numbers without leading zeros. The CGPA will contain,
at most, 2 digits after the decimal point.
Output Format
After rearranging the students according to the above rules, print the first name of each student on a separate line.
Sample Input:
5
33 Rumpa 3.68
85 Ashis 3.85
56 Samiha 3.75
19 Samara 3.75
22 Fahim 3.76
Sample Output:
Ashis
Fahim
Samara
Samiha
Rumpa*/
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;
}
}
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((o2.getCgpa()-o1.getCgpa())==0 && o1.getFname().equals(o2.getFname())) {return o2.getId()-o1.getId();}
else if((o2.getCgpa()-o1.getCgpa())==0){return o1.getFname().compareTo(o2.getFname());}//alphabetically
else if (o2.getCgpa()<o1.getCgpa()){return -1;}
return 1;
}
});
for (Student each : studentList) {
System.out.println(each.getFname());
}
}
}
/*EXTREMELY BEAUTIFUL SOLUTION
Collections.sort(studentList, Comparator.comparing(Student :: getCgpa).reversed().
thenComparing(Student :: getFname).thenComparing(Student :: getId));*/