Java 1.8版本之后的Lambda表达式
1.Lambda表达式
Lambda表达式在1.7版本之前是无法表达的,在1.8之后为了简化代码,出现了Lambda表达式。 这里我创建了两个test.java类,来比较一下。
test.java( 正常表示 )
interface IMessage { public void send(String str); } public class test { public static void main(String[] args) { IMessage msg = new IMessage() { public void send(String str) { System.out.println("发送消息: " + str); } }; //1.7版本的正常表示 msg.send("www.baidu.com"); } }
test.java( Lamda表达式的状态 )
interface IMessage { public void send(String str); } public class test { public static void main(String[] args) { IMessage msg = ( str ) -> { System.out.println("发送消息: " + str); }; //1.8之后版本的Lambda的简单表达式 msg.send("www.baidu.com"); } }
注意事项
Lambda表达式如果要想使用,那么必须有一个重要的实现要求:SAM(Single Abstract Method),只有一个抽象方法,以之前的IMessage接口为例,在这个接口里面发现只是提供有一个send()方法,除此之外没有任何的其他方法定义,所以这样的接口被称为函数式接口,而只有函数式接口才可以被Lambda表达式所使用的。
2.函数式接口注解
在使用Lambda表达式的接口时,要养成使用函数式接口的这个注解:
@FunctionalInterface
例如:
@FunctionalInterface interface IMessage { public void send(String str); }
这样可以预防错误!
3.Lambda表达式的几种格式
对于Lambda表达式而言,提供有如下几种格式:
1.方法没有参数: () -> { }; 例如: interface IMessage { public void send(); } public class test { public static void main(String[] args) { IMessage msg = ( str ) -> { System.out.println("发送消息: www.baidu.com"); }; msg.send(); } } 2.方法有参数: (参数,参数) -> { } interface Math { public void add(int x,int y); } public class test { public static void main(String[] args) { IMessage msg = (t1,t2 ) -> { return t1+t2; }; System.out.println( msg.add(10,20) ); } } 3.如果现在只有一行语句返回: (参数 ,参数,...) -> 语句;(这个语句叫做返回语) interface Math { public void add(int x,int y); } public class test { public static void main(String[] args) { IMessage msg = (t1,t2 ) -> t1+t2; System.out.println( msg.add(10,20) ); } }
上一篇:
IDEA上Java项目控制台中文乱码