一、代码测试案例
package demo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import entity.Users;
public class Test {
public static void main(String[] args) {
List<Users> list = new ArrayList<>();
list.add(new Users("sio", "23", "女"));
list.add(new Users("tom", "25", "男"));
list.add(new Users("bom", "29", "男"));
list.add(new Users("any", "29", "女"));
Collections.sort(list, new Comparator<Users>() {
@Override
public int compare(Users o1, Users o2) {
return o1.getAge().compareTo(o2.getAge());
}
});
System.out.println("jdk8之前的排序:");
list.forEach(System.out::println);
System.out.println();
list.sort((Users u1, Users u2) -> u1.getAge().compareTo(u2.getAge()));
System.out.println("jdk8 lambda排序,带参数类型:");
list.forEach(System.out::println);
System.out.println();
list.sort((u1, u2) -> u1.getAge().compareTo(u2.getAge()));
System.out.println("jdk8 lambda排序,不带参数类型:");
list.forEach(System.out::println);
System.out.println();
Collections.sort(list, Comparator.comparing(Users::getAge));
System.out.println("jdk8 升序排序:");
list.forEach(System.out::println);
System.out.println();
Collections.sort(list, Comparator.comparing(Users::getAge).reversed());
System.out.println("jdk8 降序排序:");
list.forEach(System.out::println);
System.out.println();
Collections.sort(list, Comparator.comparing(Users::getAge).thenComparing(Users::getName));
System.out.println("jdk8 组合排序,先按年纪排序,年纪相同的按名称排序:");
list.forEach(System.out::println);
}
}
二、效果图如下
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c9e3f6003ac46708d15407fe7cc19373.png#pic_center)