JDK1.8的新特性之lambda表达式的三种引用

package com.ilike.test;

import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

import org.junit.Test;

/**
*
* @author 桑伟东
* 一、方法引用:若lambda体中的内容已经有方法已经实现了,我们可以使用“方法引用”
* (可以理解为方法引用是lambda表达式的另外一种表现形式)
*
* 主要有三种语法格式
*
* 对象::实例方法名
*
* 类::静态方法名
*
* 类::实例方法名
*
* 注意:
* ①Lambda体中掉欧阳方法的参数列表和方法的返回值类型要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
* ②若Lambda参数列表中的第一个参数是实例方法的调用者,而第二个参数是实例方法的参数时,可以使用ClassName::Method
*
* 二、构造器引用:
* 格式:
* ClassName::new
* 注意:需要调用的构造器的参数列表要与函数式接口中抽象方法的参数列表保持一致
*
* 三、数组引用:
* 格式:
* Type[]::new
*
*/
public class TestMethodInf {

// 数组引用:
@Test
public void test7() {
    Function f = (x) -> new String[x];

    Function f2 = String[]::new;
    String[] s = f2.apply(10);
    System.out.println(s.length);
}

// 构造器引用
@Test
public void test5() {
    Supplier sp = () -> new Student();

    // 构造器引用方式
    Supplier sp2 = Student::new;
    Student student = sp2.get();
    System.out.println(student);
}

@Test
public void test6() {
    Function f = (x) -> new Student(x);

    Function f2 = Student::new;
    Student student = f2.apply("桑伟东");
    System.out.println(student);
}

// 类::实例方法名
@Test
public void test4() {
    BiPredicate bp = (x, y) -> x.equals(y);
    BiPredicate bp2 = String::equals;
}

// 类::静态方法名
@Test
public void test3() {
    Comparator comparator = (x, y) -> Integer.compare(x, y);
    Comparator comparator2 = Integer::compare;
}

// 对象::实例方法名
@Test
public void test1() {
    PrintStream ps = System.out;
    Consumer consumer = (x) -> ps.println(x);

    PrintStream ps1 = System.out;
    Consumer consumer2 = ps1::println;

    Consumer consumer3 = System.out::println;
    consumer3.accept("djgshdfghjhfgldfg");
}

@Test
public void test2() {
    Student student = new Student();
    Supplier s = () -> student.getAge();
    Integer age = s.get();
    System.out.println(age);

    Supplier s2 = student::getName;
    String name = s2.get();
    System.out.println(name);
}

}

package com.ilike.test;

public class Student {
private String name;

private int age;

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 Student(String name, int age) {
    this.name = name;
    this.age = age;
}

public Student(String name) {
    this.name = name;
}

public Student() {

}

@Override
public String toString() {
    return "Student [name=" + name + ", age=" + age + "]";
}

}

你可能感兴趣的:(java技术)