1、首先介绍Stream流排序, 因为这个玩意真的太方便了
public class SortDemo {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
list.add(new User(5, "张三"));
list.add(new User(2, "李四"));
list.add(new User(3, "王五"));
List<User> result = list.stream().sorted(Comparator.comparingInt(u -> u.id)).collect(Collectors.toList());
System.out.println(result);
}
static class User{
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
}
}
2、自己项目中类可以是实现Comparable接口, 这样就可以借用java自带的排序api, 比如Collections, TreeSet等
public class SortDemo {
public static void main(String[] args) {
TreeSet<User> treeSet = new TreeSet<>();
treeSet.add(new User(5, "张三"));
treeSet.add(new User(2, "李四"));
treeSet.add(new User(3, "王五"));
System.out.println(treeSet);
}
static class User implements Comparable<User>{
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
@Override
public int compareTo(User o) {
return this.id - o.id;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
}
3、如果是二方/三方包中类可以基于Comparator接口, 这样也可以借用java自带的排序api
// 1中stream流中就是借用了这个接口
public static void main(String[] args) {
List<User> list = new ArrayList<>();
list.add(new User(5, "张三"));
list.add(new User(2, "李四"));
list.add(new User(3, "王五"));
List<User> result = list.stream().sorted(Comparator.comparingInt(u -> u.id)).collect(Collectors.toList());
System.out.println(result);
}