使用Comparator自定义排序
@FunctionalInterface public interface Comparator<T> { // @param o1 the first object to be compared. // @param o2 the second object to be compared. // @return a negative integer, zero, or a positive integer as the // first argument is less than, equal to, or greater than the second. int compare(T o1, T o2); }
根据源码可知,如果o1大于o2返回正数,如果o1小于o2返回负数,如果o1等于o2返回0
使用stream流进行排序以及比较大小
@Data
@Accessors(chain = true)
public class Stu {
private Integer age;
private String name;
}
@Test
public void test05() {
List<Stu> stuList = new ArrayList<>();
stuList.add(new Stu().setAge(1005));
stuList.add(new Stu().setAge(1008));
stuList.add(new Stu().setAge(1004));
System.out.println("按age默认从小到大排序");
stuList.stream().sorted(Comparator.comparingInt(Stu::getAge)).collect(Collectors.toList()).forEach(System.out::println);
System.out.println("按age从大到小排序");
stuList.stream().sorted(Comparator.comparingInt(stu -> -stu.getAge())).collect(Collectors.toList()).forEach(System.out::println);
System.out.println("求age最大值");
stuList.stream().max(Comparator.comparing(Stu::getAge)).ifPresent(System.out::println);
System.out.println("求age最小值");
stuList.stream().min(Comparator.comparing(Stu::getAge)).ifPresent(System.out::println);
}