对Lambda表达式的总结

关于java8的特性:lambda表达式

lambda表达式可以理解为一种匿名函数:没有名称、有参数列表、函数主体、返回类型,可能还会有异常的列表。

lambda表达式:(参数) -> 表达式 或者是 (参数) -> { java语句; }

函数式接口

什么是函数式接口

函数式接口就是仅仅定义了一个抽象方法的接口,类似于predicate、comparator和runnable接口。

@FunctionalInterface

@FunctionalInterface 函数式接口都带有这个注解,这个注解表示这个接口会被设计为函数式接口。

什么是行为参数化

一个方法接受多个不同的行为作为参数,并在内部使用它们,完成不同行为的能力。

必须知道的四大核心函数式接口

Consumer接口源码(有参,无返回值)

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

使用方法:

public static void test1() {
        Consumer<Float> consumer = (x) -> {System.out.println("He consumes " + x + "¥");};
        consumer.accept((float) 50.5);
    }

Supplier接口源码(无参,有返回值)

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

使用方法:

 public static void test2(){
        Supplier<Integer> supplier =
                () -> {
                    String s = "hello world";
                    Integer n = s.length();
                    return n;
                };

        Integer n = supplier.get();
        System.out.println("n 的值为:" + n);
    }

Function接口源码(有参,有返回值)

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

使用方法:

public static void test3(){
        Function<List<Integer>, Integer> function = 
                (x) -> {
                    int n = x.size();
                    Integer value = x.get(n-1);
                    return value;
                };

        List<Integer> list = Arrays.asList(1, 2, 3);        
        Integer lastValue = function.apply(list);
        System.out.println("The lastValue is " + lastValue);
    }

Predicate接口源码(有参,返回值为boolean)

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}

使用方法:

public static void test4(){
        Predicate<String> predicate = 
                (x) -> {
                    int n = x.length();
                    if (n > 10) {
                        System.out.println("n 大于 10");
                        return true;
                    }else {
                        System.out.println("n 小于 10");
                        return false;
                    }
                };

        predicate.test("Hello world!");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值