The collection is sorted according to a certain attribute of the generic type, and the Collecions.sort method can be customized
Method 1:
Generics (custom classes) need to implement the Comparable interface and override the compareTo method
The implementation code is as follows
Custom Person class
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//此处省略get,set方法
//这里是重点,是按照年龄进行排序
@Override
public int compareTo(Person o) {
return o.getAge()-this.getAge();
}
}
test
public class Main {
public static void main(String[] args) {
ArrayList<Person> list=new ArrayList<>();
list.add(new Person("小明",19));
list.add(new Person("小红",18));
list.add(new Person("小王",20));
for (Person p:list) {
System.out.println(p.getName()+":"+p.getAge());
}
Collections.sort(list);
System.out.println("按照年龄进行排序后=======================");
for (Person p:list) {
System.out.println(p.getName()+":"+p.getAge());
}
}
}
Method two:
person class
public class Person1 {
private String name;
private int age;
public Person1(String name, int age) {
this.name = name;
this.age = age;
}
//省略get,set
}
test
ArrayList<Person1> list=new ArrayList<>();
list.add(new Person1("小明",19));
list.add(new Person1("小红",18));
list.add(new Person1("小王",20));
for (Person1 p:list) {
System.out.println(p.getName()+":"+p.getAge());
}
//实现Comparator接口并重写compare方法
Collections.sort(list, new Comparator<Person1>() {
@Override
public int compare(Person1 o1, Person1 o2) {
return o2.getAge()-o1.getAge();
}
});
System.out.println("按照年龄进行排序后=======================");
for (Person1 p:list) {
System.out.println(p.getName()+":"+p.getAge());
}