Java实现List自定义排序
废话不多说,直接上代码
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class User { public static void main(String[] args) { List<User> list = new ArrayList<>(); list.add(new User("张三",18)); list.add(new User("诸葛亮",69)); list.add(new User("孙悟空",500)); list.add(new User("周杰伦",45)); list.add(new User("郭德纲",60)); list.add(new User("秦始皇",5000)); System.out.println("排序前:"); System.out.println(list); Collections.sort(list, new Comparator<User>() { @Override public int compare(User o1, User o2) { int age1 = o1.getAge(); int age2 = o2.getAge(); if (age1 == age2) { return 0; }else { // 从小到大 return age1 > age2 ? 1 : -1 ; // 如果需要从大到小,可以将return的值反过来即可 } } }); System.out.println("排序后:"); System.out.println(list); } private String name; private int 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; } public User(String name, int age) { super(); this.name = name; this.age = age; } public User() { super(); } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }