函数式接口
函数式接口指的是只有一抽象方法的接口,比如java.lang.Runnable就是一个函数式接口,在Runnable接口中只有一个run()方法:
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
函数式接口可以使用注解@FunctionalInterface标。使用@FunctionalInterface标的接口中只能有一个抽象方法如果有多个的话,编译阶段就会报错。
Lambda表达式本身就是函数式接口的一个实例
当需要对一个函数式接口实例化的时候,可以考虑使用Lambda表达式。
Runnable r = ()->System.out.println("hahaha......");
示例:
- 自定义函数式接口
@FunctionalInterface
public interface NewInter {
int PAGE_NUM = 1234;
// 抽象方法
int fun1(int a ,int b);
default void fun2(){
System.out.println("fun2");
}
//接口中的静态方法只能通过接口名调用
static void fun3(){
System.out.println("fun3");
}
}
- 使用函数式接口
public static void main(String[] args) {
NewInter inter = (a,b)->a+b;
int res = inter.fun1(11, 22);
System.out.println(res);
inter.fun2();
NewInter.fun3();
}
Java8新增的函数式接口
为了推动函数式编程,Java8在 java.util.function 包下为我们提供了大量好用的函数式接口:
接口名抽象方法描述符 P r e d i c a t e \color{#ca0c16}{Predicate} Predicateboolean test(T t)T -> booleanBiPredicateboolean test(T t, U u)( T, U ) -> boolean C o n s u m e r \color{#ca0c16}{Consumer} Consumervoid accept(T t)T -> voidBiConsumervoid accept(T t, U u)( T, U ) -> void F u n c t i o n < T , R > \color{#ca0c16}{Function} FunctionR apply(T t)T -> RBiFunctionR apply(T t, U u)( T, U ) -> R S u p p l i e r \color{#ca0c16}{Supplier} SupplierT get()void -> TIntFunctionR apply(int value)int-> RLongFunctionR apply(long value)long-> RDoubleFuncionR apply(double value)double-> RToIntFunctionint applyAsInt(T value)T -> intToLongFunctionlong applyAsLong(T value)T -> longToDoubleFunctiondouble applyAsDouble(T value)T -> double开发过程中如果需要建议优先使用系统提供的函数式接口。 为了能够更好的使用Lambda简化程序编写,上面接口需要大家认真记忆并熟练掌握。
示例:采用Lambda可以将一段代码作为参数传递给方法
public class DemoTest {
public static void main(String[] args) {
boolean res1 = fun1(11, a -> a > 8);
System.out.println(res1);
fun2("ZhangSan",a-> System.out.println(a));
String res3 = fun3("china", a -> a.toUpperCase(Locale.ROOT));
System.out.println(res3);
Integer res4 = fun4(() -> new Random().nextInt());
System.out.println(res4);
}
public static boolean fun1(int digit , Predicate predicate){
return predicate.test(digit);
}
public static void fun2(String str, Consumer consumer){
consumer.accept(str);
}
public static String fun3(String str, Function function){
return function.apply(str);
}
public static Integer fun4(Supplier supplier){
return supplier.get();
}
}