Collections 中有一个方法叫做sort可以对集合中的内容进行排序,要使用这个sort方法进行排序的集合,里面的泛型必须实现Comparable接口,实现这个接口的对象才具备排序的功能,这种排序自然排序。
第一种:Comparable 排序接口,若一个类实现了Comparable接口,就意味着“该类支持排序”
public class User implements Comparable<User> { private String name; private int age; private int id; public User(String name, int age, int id) { this.name = name; this.age = age; this.id = id; } public String getName() { return name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", id=" + id + '}'; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public User() { } // 重写compareTo方法 @Override public int compareTo(User o) { // 先比较age int i = this.getAge() - o.getAge(); if (i == 0) { //age相等,再比较id int j = this.getId() - o.getId(); return j; } return i; } }
测试类
public class Test { public static void main(String[] args) { List<User> list = new ArrayList<>(); list.add(new User("张三", 19, 4)); list.add(new User("李四", 18, 2)); //Collections.addAll(list, new User("王五", 17, 3), new User("赵六", 17, 1)); list.add(new User("王五", 17, 3)); list.add(new User("赵六", 17, 1)); System.out.println("排序前:" + list); Collections.sort(list); System.out.println("排序后:" + list); } }
结果:
排序前:[User{name='张三', age=19, id=4}, User{name='李四', age=18, id=2}, User{name='王五', age=17, id=3}, User{name='赵六', age=17, id=1}]
排序后:[User{name='赵六', age=17, id=1}, User{name='王五', age=17, id=3}, User{name='李四', age=18, id=2}, User{name='张三', age=19, id=4}]
第二种:Comparator比较器接口
我们若需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口);我们可以建立一个“比较器”来进行排序。这个“比较器”只需要实现Comparator接口即可。
public class Test6 { public static void main(String[] args) { List<User> list = new ArrayList<>(); list.add(new User("张三", 19, 4)); list.add(new User("李四", 18, 2)); list.add(new User("王五", 17, 3)); list.add(new User("赵六", 17, 1)); Collections.sort(list, new Comparator<User>() { @Override public int compare(User o1, User o2) { int i = o1.getAge() - (o2.getAge()); if (i == 0) { int j = o1.getId() - o2.getId(); return j; } return i; } }); System.out.println(list); // [User{name='赵六', age=17, id=1}, User{name='王五', age=17, id=3}, User{name='李四', age=18, id=2}, User{name='张三', age=19, id=4}] } }