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<Student> students=new ArrayList<>();
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<Student>() {
@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 + '\'' +
'}';
}
}