-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjSorting.java
More file actions
60 lines (48 loc) · 1.68 KB
/
ObjSorting.java
File metadata and controls
60 lines (48 loc) · 1.68 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
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Students {
String name;
int iD;
double cgpa;
public Students(String name, int iD, double cgpa) {
this.name = name;
this.iD = iD;
this.cgpa = cgpa;
}
}
public class ObjSorting {
public static void main(String[] args)
{
try {
ArrayList<Students> list = new ArrayList<>();
list.add(new Students("A", 7,3.77)); // creating object (without reference)
list.add(new Students("B", 8,3.77));
list.add(new Students("C", 4,3.5));
list.add(new Students("D", 1,3.88));
System.out.println("---Before sorting ---");
printStudentData(list);
System.out.println("---After sorting ---");
Collections.sort(list, new Comparator<Students>() { //anonymous
@Override
public int compare(Students left, Students right) {
if(right.cgpa > left.cgpa)
return -1; // -1 : goes to the left
if(left.cgpa > right.cgpa)
return 1; // goes to the right
return left.name.compareTo(right.name); //small UP ; big DOWN
}
});
printStudentData(list); //method is to be a static as it's inside main method
}
catch(Exception e) {
e.printStackTrace();
}
}
static void printStudentData(ArrayList<Students> list) {
//for-each is smarter
for (Students s : list) {
System.out.println(s.name + " " + s.iD + " " + s.cgpa);
}
}
}