实现效果
编写代码
1、实体类对象实现Comparable接口重写compareTo方法
public class User implements Comparable<User>{
private String name;
private Integer age;
public User() {
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(User o) {
return this.age.compareTo(o.getAge());
}
}
2、使用demo
public class ListBySort {
public static void main(String[] args) {
List<User> list=new ArrayList<>();
User user = new User("张三",19);
list.add(user);
User user1 = new User("李四",20);
list.add(user1);
User user2 = new User("王五",16);
list.add(user2);
System.out.println("升序排序前:"+list);
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o1.getAge().compareTo(o2.getAge());
}
});
System.out.println("升序排序后:"+list);
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o2.getAge().compareTo(o1.getAge());
}
});
System.out.println("降序排序后:"+list);
}
}
Java8之后使用stream().sorted()排序
同样需要对实体对象实现Comparable接口重写compareTo方法
使用同样的测试数据
public class ListByStream {
public static void main(String[] args) {
List<User> list=new ArrayList<>();
User user = new User("张三",19,175);
list.add(user);
User user1 = new User("李四",20,177);
list.add(user1);
User user2 = new User("王五",16,180);
list.add(user2);
User user3 = new User("赵六",16,170);
list.add(user3);
System.out.println("升序排序前:"+list);
List<User> collect = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
System.out.println("升序排序后:"+collect);
List<User> collect1 = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
System.out.println("降序排序后:"+collect1);
//对相同的年龄再次按照升高排序
List<User> collect2 = list.stream()
.sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getHeight))
.collect(Collectors.toList());
System.out.println("降序排序后再对升高升序排序:"+collect2);
}
}
参考文章:
1.https://www.cnblogs.com/wdzhz/p/11583359.html
2.https://www.cnblogs.com/codecat/p/10873757.html