Java
Beginner
1 min read
Generic Interfaces: Comparable and Comparator
Example
import java.util.*;
class Student implements Comparable<Student> {
String name;
double gpa;
Student(String name, double gpa) {
this.name = name;
this.gpa = gpa;
}
@Override
public int compareTo(Student other) {
// Natural order: ascending by name
return this.name.compareTo(other.name);
}
@Override
public String toString() {
return name + "(" + gpa + ")";
}
}
public class ComparableDemo {
public static void main(String[] args) {
List<Student> students = new ArrayList<>(List.of(
new Student("Zoe", 3.8),
new Student("Alice", 3.5),
new Student("Bob", 3.9),
new Student("Carol", 3.5)
));
// Natural ordering (Comparable)
Collections.sort(students);
System.out.println("By name: " + students);
// Comparator: descending GPA, then name
Comparator<Student> byGpaDesc = Comparator
.comparingDouble(Student::gpa)
.reversed()
.thenComparing(s -> s.name);
students.sort(byGpaDesc);
System.out.println("By GPA desc: " + students);
// TreeSet uses natural order
TreeSet<Student> tree = new TreeSet<>(students);
System.out.println("TreeSet first: " + tree.first());
}
}