-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathComparableAndComparatorExample.java
More file actions
79 lines (65 loc) · 2.07 KB
/
ComparableAndComparatorExample.java
File metadata and controls
79 lines (65 loc) · 2.07 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
package Collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
// A class that implements Comparable
class Student implements Comparable<Student> {
private int id;
private String name;
private double gpa;
public Student(int id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getGpa() {
return gpa;
}
@Override
public String toString() {
return "Student{" + "id=" + id + ", name='" + name + '\'' + ", gpa=" + gpa + '}';
}
// Default sorting by ID
@Override
public int compareTo(Student other) {
return Integer.compare(this.id, other.id);
}
}
// A comparator to sort by name
class SortByName implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
return a.getName().compareTo(b.getName());
}
}
// A comparator to sort by GPA
class SortByGpa implements Comparator<Student> {
@Override
public int compare(Student a, Student b) {
return Double.compare(b.getGpa(), a.getGpa()); // Descending order
}
}
public class ComparableAndComparatorExample {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(3, "Charlie", 3.8));
students.add(new Student(1, "Alice", 3.5));
students.add(new Student(2, "Bob", 3.9));
// Sorting using Comparable (default sorting by ID)
Collections.sort(students);
System.out.println("Sorted by ID (Comparable): " + students);
// Sorting using Comparator (by name)
Collections.sort(students, new SortByName());
System.out.println("Sorted by Name (Comparator): " + students);
// Sorting using Comparator (by GPA)
Collections.sort(students, new SortByGpa());
System.out.println("Sorted by GPA (Comparator): " + students);
}
}