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
interface, and then call theCollections.sort(List)
method to sort. The other method is that the class does not implement theComparable
interface, When sorting, use theCollections.sort(List, Comparator
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
public class Student implements Comparable{ 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 + '}'; } }
2. Sort by implementing the Comparable
public class Client { public static void main(String[] args){ Liststudents = 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 () { @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()); } } }
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!