您好,登錄后才能下訂單哦!
主要的三種語法格式:
注意:
若Lambda參數列表中的第一參數是 實例方法的調用者,而第二個參數是 實例方法的參數時,可以使用ClassName::method
public class Employee {
private String name;
private int age;
private double salary;
public Employee() {
super();
}
public Employee(int age){
this.age = age;
}
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
//對象::實例方法名
@Test
public void test1(){
PrintStream ps1 = System.out;
Consumer<String> con = (x) -> ps1.println(x);
PrintStream ps = System.out;
Consumer<String> con1 = ps::println;
Consumer<String> con2 = System.out::println;
con2.accept("abcdef");
}
@Test
public void test2(){
Employee employee = new Employee();
Supplier<String> sup = () -> employee.getName();
String str = sup.get();
System.out.println(str);
Supplier<String> sup2 = employee::getName;
String str2 = sup2.get();
System.out.println(str2);
}
//類:靜態方法名
@Test
public void test3(){
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
Comparator<Integer> com1 = Integer::compare;
}
格式:ClassName::new
注意:需要調用的構造器的參數列表要與函數式接口中抽象方法的參數列表保持一致
public class Employee {
private String name;
private int age;
private double salary;
public Employee() {
super();
}
public Employee(int age){
this.age = age;
}
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
//構造器引用
@Test
public void test5(){
Supplier<Employee> sup = () -> new Employee();
//構造器引用方式
Supplier<Employee> sup2 = Employee::new;
Employee employee = sup2.get();
System.out.println(employee);
}
@Test
public void test6(){
Function<Integer, Employee> fun = (x) -> new Employee(x);
Function<Integer, Employee> fun2 = Employee::new;
Employee emp = fun2.apply(101);
System.out.println(emp);
}
格式:Type[ ]::new;
//數組引用
@Test
public void test7(){
Function<Integer, String[]> fun = (x) -> new String[x];
String[] strs = fun.apply(10);
System.out.println(strs.length);
Function<Integer, String[]> fun2 = String[]::new;
String[] strs2 = fun2.apply(20);
System.out.println(strs2.length);
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。