函数式接口

2018-12-19  本文已影响0人  CC晨_程序小生

函数式接口

函数式接口通过一个单一的功能来表现。例如,带有单个compareTo方法的比较接口,被用于比较的场合。Java 8 定义了大量的函数式接口来广泛地用于lambda表达式。

Java 8 引入的一个核心概念是函数式接口(Functional Interfaces)。通过在接口里面添加一个抽象方法,这些方法可以直接从接口中运行。如果一个接口定义唯一一个抽象方法,那么这个接口就成为函数式接口。同时,引入了一个新的注解:@FunctionalInterface。可以把他它放在一个接口前,表示这个接口是一个函数式接口。这个注解是非必须的,只要接口只包含一个方法的接口,虚拟机会自动判断,不过最好在接口上使用注解 @FunctionalInterface 进行声明。在接口中添加了 @FunctionalInterface 的接口,只允许有一个抽象方法,否则编译器也会报错。
部分函数式接口列表

更多的接口可以参考Java 8官方API手册:java.lang.Annotation Type FunctionalInterface。在实际使用过程中,加有@FunctionalInterface注解的方法均是此类接口,位于java.util.Funtion包中

一个例子

源代码:函数式编程

public class NewFeaturesTester {
    public static void main(String args[]){
        List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

        System.out.println("All of the numbers:");

        eval(list, n->true);

        System.out.println("Even numbers:");
        eval(list, n-> n%2 == 0 );

        System.out.println("Numbers that greater than  5:");
        eval(list, n -> n > 5 );
    }

    public static void eval(List<Integer> list, Predicate<Integer> predicate) {
        for(Integer n: list) {
            if(predicate.test(n)) {
                System.out.println(n);
            }
        }
    }
}

输出结果:

All of the numbers:
0
1
2
3
4
5
6
7
8
9
Even numbers:
0
2
4
6
8
Numbers that greater than  5:
6
7
8
9
上一篇 下一篇

猜你喜欢

热点阅读