We need to sort the objects of the class according to a certain attribute (or multiple attributes) in the class. There are two ways to achieve this. One method is class implementation. Comparable<T>
interface, and then call the Collections.sort(List)
method to sort. The other method is that the class does not implement the Comparable<T>
interface, When sorting, use the Collections.sort(List, Comparator<T>)
method and implement the Comparator
Free learning video tutorial recommendation: java video tutorial
First create a simple student class:
public class Student { private String name; private int age; public Student() {} public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
1. Implement Comparable 2. Sort by implementing the Comparable<T> interface in the Collections.sort() method Recommended related article tutorials:Introduction to java programming The above is the detailed content of How to sort objects of a class in java. For more information, please follow other related articles on the PHP Chinese website!public class Student implements Comparable<Student>{
private String name;
private int age;
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/**
* 将对象按姓名字典序升序排序
* @param o
* @return
*/
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Client {
public static void main(String[] args){
List<Student> students = new ArrayList<>();
students.add(new Student("a", 18));
students.add(new Student("c", 19));
students.add(new Student("b", 20));
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge()>o2.getAge()? -1:(o1.getAge()==o2.getAge()? 0:1);
}
});
for(Student student:students){
System.out.println(student.toString());
}
}
}