list按照某个元素进行排序

时间:2022-02-15 21:12:53
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; public class Sort { private int age ; private String name; public Sort(int age, String name) {
this.age = age;
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "Sort{" +
"age=" + age +
", name=" + name +
'}';
} public static void main(String args[]) { List<Sort> sorts = new ArrayList<>(); sorts.add(new Sort(18,"ww"));
sorts.add(new Sort(12,"wf"));
sorts.add(new Sort(13,"wg"));
sorts.add(new Sort(19,"wa"));
sorts.add(new Sort(16,"wb")); System.out.println("排序前的结果:"+sorts.toString());
Collections.sort(sorts, new Comparator<Sort>(){
/*
* int compare(Person p1, Person p2) 返回一个基本类型的整型,
* 返回负数表示:p1 小于p2,
* 返回0 表示:p1和p2相等,
* 返回正数表示:p1大于p2
*/
public int compare(Sort p1, Sort p2) {
//按照Person的年龄进行升序排列
if(p1.age > p2.age){
return 1;
}
if(p1 == p2){
return 0;
}
return -1;
}
});
System.out.println("排序后的结果:"+sorts.toString()); }
}

执行结果:

排序前的结果:[Sort{age=18, name=ww}, Sort{age=12, name=wf}, Sort{age=13, name=wg}, Sort{age=19, name=wa}, Sort{age=16, name=wb}]
排序后的结果:[Sort{age=12, name=wf}, Sort{age=13, name=wg}, Sort{age=16, name=wb}, Sort{age=18, name=ww}, Sort{age=19, name=wa}]