函数式接口
函数式接口在Java中是指:有且仅有一个抽象方法的接口。
函数式接口,即适用于函数式编程场景的接口。而Java中的函数式编程体现就是Lambda,所以函数式接口就是可以适用于Lambda使用的接口。只有确保接口中有且仅有一个抽象方法,Java中的Lambda才能顺利地进行推导。
Java 8中加入了@FunctionalInterface。
该注解可用于一个接口的定义上:
使用该注解来定义接口,编译器将会强制检查该接口是否确实有且仅有一个抽象方法,否则将会报错。
自定义的函数式接口。只有有一个抽象方法时才不会报错
@FunctionalInterface
public interface MyFuncation {
void method();
}
/*自定义函数式接口*/
public class TetsdemoALL {
public static void method(MyFuncation my){
my.method();
}
public static void main(String[] args) {
/*method(new MyFuncation() {
@Override
public void method() {
System.out.println("自定义抽象方法:");
}
});*/
method(()-> System.out.println("自定义抽象方法:"));
}
}
函数式接口可以作为方法的参数和返回值类型,上面这个代码就是Lambda表达式作为自方法的参数。常见的还有Runnable接口中的run方法,compatator接口中的compar。
Lambda表达式对代码的优化:lambda表达式作为代码块,在做方法的参数时是不会被执行的,只有在调用时才会被执行代码块中的内容。所以在接口中定义抽象方法,用Lambda作为方法的参数,把要优化的代码放在lambda代码块中。
public class Test {
public static void main(String[] args) {
String s1 = "你";
String s2 = "好";
String s3 = "java";
getMassage(1, s1 + s2 + s3);
}
public static void getMassage(int level, String s) {
if (level == 1) {
System.out.println(s);
}
}
}
改进代码:
@FunctionalInterface
public interface GetMassage {
void getMassage();
}
public class test {
public static void main(String[] args) {
String s1="你";
String s2="好";
String s3="java";
getMassage(1,()-> System.out.println(s1+s2+s3));
}
public static void getMassage(int leveal, GetMassage mass){
if (leveal==1){
mass. getMassage();
}
}
}
Lambda表达式作为参数和返回值:
作为参数:
public class RunnableTest {
public static void main(String[] args) {
//new Thread(()-> System.out.println("线程被执行了:")).start();
startAThread(()-> System.out.println("线程被执行了。"));
}
public static void startAThread(Runnable run){ //run为接口的实现
new Thread(run).start();
}
}
//做返回值:
import java.util.Comparator;
public class CompartorTest {
public static void main(String[] args) {
int compare = compTest().compare("asdds", "bcdasda");
System.out.println(compare);
}
public static Comparator<String> compTest(){ //返回一个lambda表达
return (a,b)->b.length()-a.length();
}
}