可以这么说,函数式接口中只能有一个抽象方法,可以有实现的静态方法;
@FunctionalInterface这个只是一个编译级的注解,用来检测你编写的函数式接口是否有错的
@FunctionalInterface
interface TestInterface {
public final static String value ="111";
static void staticFuc(){
}
void Test();
}
他共有四种核心的函数式接口
一、功能性接口:Function 接收一个功能参数t,并返回一个功能结果R。
package java.util.function;
import java.util.Objects;
@FunctionalInterface
public interface Function{
R apply(T t);
default Functioncompose(Function super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default FunctionandThen(Function super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static Functionidentity() {
return t -> t;
}
}
举例:可以简写为 Functionfunction = (str) -> "hello,"+str;
Functionfunction = (str) ->{
return "hello,"+str;
};
String str = function.apply("Tassel");
System.out.println(str);
二、断言性接口:Predicate 主要用到test方法其中参数t为输入参数,如果输入参数符合断言则返回true,否则false
package java.util.function;
import java.util.Objects;
@FunctionalInterface
public interface Predicate{
boolean test(T t);
default Predicateand(Predicate super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
default Predicatenegate() {
return (t) -> !test(t);
}
default Predicateor(Predicate super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static PredicateisEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
举例子:下面的等价于"Hello".equalsIgnoreCase(t) //t:输入参数
Predicatepredicate = "Hello"::equalsIgnoreCase;
System.out.println(predicate.test("Hello"));
三、供给性接口:Supplier 不接收任何参数 但有返回值
@FunctionalInterface
public interface Supplier{
T get();
}
Supplier supplier = "Hello"::toLowerCase;
System.out.println(supplier);
四、消费性接口:Consumer只接收一个参数t,但是没有返回值。
package java.util.function;
import java.util.Objects;
@FunctionalInterface
public interface Consumer{
void accept(T t);
default ConsumerandThen(Consumer super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
Consumerconsumer = System.out ::println;
consumer.accept("1111");
ArrayListarrayList = new ArrayList<>();
Consumerconsumer = (e)-> e.add("111");