Question: How do you sort by Student name
or age
?
We can use Comparable, and the Custom class should extend "Comparable" class and override the compareTo method.
# Comparable
Comparable class has only one method:
public int compareTo(){ | |
return 0 ; // <- return -ve or +ve; | |
} |
public int compareTo(){ | |
return a - b ; | |
// b > a, so if sorted in order , | |
// then it will return a negative | |
// output : ab |
# Sort by custom class
- your custom class
implement Comparable <YourClass>
- override comparaTo(), something like below
return - this.getName().compareTo(obj.getName()) ; |
3 in the main(), use
Collections.sort()`
ArrayList<Student> classroom = new ArrayList<>(); | |
classroom.add(new Student("Tony", 12)); | |
classroom.add(new Student("hanyu", 9)); | |
classroom.add(new Student("tiff", 10)); | |
classroom.add(new Student("Alice", 6)); | |
classroom.add(new Student("Kelly",15)); | |
Collections.sort(classroom); | |
classroom.forEach(student -> { | |
System.out.println(student); | |
}); | |
} |
remember to Override : toString()
public String toString() { | |
return "Student{" + | |
"name='" + name + '\'' + | |
", age=" + age + | |
'}'; |