public class ListSort { public static void main(String[] args) { List<User> userList = new ArrayList<>(); userList.add(new User("dd", 4)); userList.add(new User("aa", 6)); userList.add(new User("ee", 5)); userList.add(new User("gg", 6)); List<User> userList2 = new ArrayList<>(); userList.add(new User("vv", 10)); userList.addAll(userList2); Collections.sort(userList, new Comparator<User>() { @Override public int compare(User o1, User o2) { if (o1.getAge() > o2.getAge()) { return -1; } if (o1.getAge() == o2.getAge()) { return 0; } return 1; } }); for (User user : userList) { System.out.println(user.getAge() + "," + user.getName()); } } class User { String name; Integer age; public User(String name, Integer age) { this.name = name; this.age = age; } public Integer getAge() { return age; } public String getName() { return name; } } }
时间: 2024-10-10 16:09:57