DEMO1.java
package com.xiangshuai.lambda;
import java.nio.file.DirectoryStream;
import java.util.*;
//此包下提供了不少可以自由Lambda的类
import java.util.function.*;
/**
* @author lqx
* @ClassName DEMO1
* @description 排序之Lambda
* @date 2020/6/20 17:11
*/
public class DEMO1 {
public static void main(String[] args) {
List
students.add(new Student(10,"小明","ss"));
students.add(new Student(30,"小明","ss"));
students.add(new Student(20,"小明","ss"));
students.add(new Student(90,"小明","ss"));
students.add(new Student(200,"小明","ss"));
students.add(new Student(80,"小明","ss"));
students.add(new Student(1,"小明","ss"));
/*
//用法一,匿名内部类直接对象字段比较排序
Collections.sort(students, new Comparator
@Override
public int compare(Student o1, Student o2) {
return o1.getAge().compareTo(o2.getAge());
}
});
System.out.println(students);
*/
/*
//用法二,Lambda直接对象字段比较排序
Collections.sort(students, ( Student o1,Student o2)->{
return o1.getAge().compareTo(o2.getAge());
});
System.out.println(students);
*/
/*
//用法三,Lambda直接对象字段比较排序,声明类型去掉,JVM会自动去找对应类型方法
Collections.sort(students, (o1,o2)->{
return o1.getAge().compareTo(o2.getAge());
});
System.out.println(students);
*/
/*
//用法四,Lambda,静态方法调用--Student::compareAgeStatic语法的意思是调用Student的compareAgeStatic方法
//,我们ctrl+鼠标左点下compareAgeStatic可跳到compareAgeStatic方法如下:
// public static int compareAgeStatic(Student s1, Student s2){
// return s1.getAge().compareTo(s2.getAge());
// }
//可以看出其实就是用法三的简写
Collections.sort(students, Student::compareAgeStatic);
System.out.println(students);
*/
//用法五,Lambda,非静态方法调用--参考方法4,原理一模一样
Collections.sort(students, Student::compareAge);
System.out.println(students);
}
}
Student.java
package com.xiangshuai.lambda;
/**
* @author lqx
* @ClassName Student
* @description
* @date 2020/6/21 12:19
*/
public class Student {
private Integer age;
private String name;
private String address;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public static int compareAge(Student s1, Student s2){
return s1.getAge().compareTo(s2.getAge());
}
public static int compareAgeStatic(Student s1, Student s2){
return s1.getAge().compareTo(s2.getAge());
}
public Student(Integer age, String name, String address) {
this.age = age;
this.name = name;
this.address = address;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}