java 8 新特性-lambda

@FunctionalInterface

since 1.8

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface’s abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.
Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

If a type is annotated with this annotation type, compilers are required to generate an error message unless:

        *The type is an interface type and not an annotation type, enum, or class.
        *The annotated type satisfies the requirements of a functional interface.

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

大意就是:函数式接口只能有一个抽象方法,重写Object类的方法不算

@Override
public boolean equals(Object obj)

其他default和static方法,不强制有,也不强制有多少。
还有就是被这个注解注解的一定是一个接口,而不是一个注解、枚举和类什么的

不管有没有声明@FunctionalInterface注解,编译器会把符合函数式接口定义的接口视作函数式接口。

lambda表达式

为什么要有@FunctionalInterface呢,——lambda表达式

()->...;//只有一行代码
()->{
    ...
};

不要把lambda表达式视作是内部类(Don’t Treat Lambda Expressions as Inner Classes)

http://www.baeldung.com/java-8-lambda-expressions-tips

这里写图片描述
balabala一大堆,大概意思就是内部类可以改的范围不一样,如果说内部类的方位是整个类
也就是这个:这里写图片描述
那么lambda表达式的范围就是一个方法体
也就是这个:这里写图片描述

java.util.function.Predicate

Predicate 谓词

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

    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
    ...
}

Predicate 用于判断,Predicate是一个函数式接口,其functional方法是boolean test()
有4个default方法,and、negate、or、isEqual。这四个方法都会返回1个实现了Predicate的匿名内部类的一个实例,这个实例会重写Predicate的functional方法。

People criteria = new People("1","1",1,1);
People criteria2 = new People("1","1",1,2);
People test = new People("1","1",1,1);

Predicate<People> predicate = Predicate.isEqual(criteria);
Predicate<People> predicate1 = people -> people.equals(criteria);
Predicate<People> predicate2 = people -> {return  people.equals(criteria2);};

System.out.println("predicate1.test(test)"+predicate1.test(test));
System.out.println("predicate1.and(predicate2)"+predicate1.and(predicate2).test(test));

这两行代码其实是lambda在方法体中只有一行代码的时候的两种写法,都会重写匿名内部类中的方法。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/canyanruxue/article/details/80943174