Java8新特性之Lambda表达式(四)

引用

一、方法引用:若Lambda体中的内容有方法已经实现了,我们可以使用方法引用
         方法引用是Lambda表达式的另外一种表现形式
主要有三种语法格式:
1.对象::实例方法名
2.类::静态方法名
3.类::实例方法名

二、构造器引用:
格式:ClassName::new

三、数组引用:
格式:Type::new

package lambda;

import org.junit.Test;
import java.util.Comparator;
import java.util.function.*;
public class TestMethodRef {

    //对象::实例方法名
    @Test
    public void test1() {
        Consumer consumer = System.out::println;
        consumer.accept("aaa");

        Employee employee = new Employee("July", 22, 8000);
        Supplier<String> sup = employee::getName;
        String str = sup.get();
        System.out.println(str);
    }

    //类::静态方法名
    @Test
    public void test2() {
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

        Comparator<Integer> com1 = Integer::compareTo;
    }

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

        BiPredicate<String, String> bp1 = String::equals;
    }

    //构造器引用
    @Test
    public void test4() {
        Supplier<Employee> emp = () -> new Employee();

        Supplier<Employee> emp1 = Employee::new;
        Employee emp2 = emp1.get();
        System.out.println(emp2);

        Function<Integer, Employee> f1 = Employee::new;
        Employee f2 = f1.apply(101);
        System.out.println(f2);

        BiFunction<String, Integer, Employee> f3 = Employee::new;
        Employee f4 = f3.apply("张倩", 24);
        System.out.println(f4);
    }

    //数组引用
    @Test
    public void test5() {
        Function<Integer, String[]> f = (x) -> new String[x];
        String[] f1 = f.apply(10);
        for (int i = 0; i < f1.length; i++) {
            String s = f1[i];
            System.out.println(s);
        }

        Function<Integer, String[]> f2 = String[]::new;
        String[] f3 = f2.apply(10);
        for (int i = 0; i < f3.length; i++) {
            String s = f3[i];
            System.out.println(s);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值