Java 8的新特性

Functional Interface

函数式接口的定义是,必须只含有一个abstract method,它可以拥有许多static或default method(包含实现), 但是 abstract method必须只有一个。

这个abstract method表示它可以做某种行为,但是具体做什么,由调用者通过Override这个抽象方法决定。可以通过匿名内部类,或者lambda expression来完成函数方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void main(String[] args) {
    //匿名内部类
    FunctionalInterface functionalInterface = new FunctionalInterface() {
        @Override
        public void execute() {
            System.out.println("Executing functionalInterface");
        }
    };
    functionalInterface.execute();
    //lambda表达式
    FunctionalInterface functionalInterface1 = ()-> System.out.println("Executing functionalInterface1");
    functionalInterface1.execute();
}

方法引用

1
2
3
4
//Lambda
Function<String, Integer> function=(string)->string.length();
//function reference
Function<String, Integer> function1= String::length;

Function也是一种函数式接口,需要重写它的T apply(R)方法。