Lambada
原始的方法
interface IMessage{
public void send(String str);'
}
public class JavaDemo{
public static void main(String args[]){
IMessage msg = new IMessage(){
public void send(String str){
System.out.println("消息发送" + str);
}
};
msg.send("www.mldn.cn");
}
}
使用Lambada
interface IMessage{
public void send(String str);'
}
public class JavaDemo{
public static void main(String args[]){
IMessage msg = (str)->{
System.out.println("发送消息"+str);
};
msg.send("www.mldn.cn");
}
}
Lambda表达式如果要想使用,那么必须有一个重要的实现要求:SAM(single Abstract Method),只有一个抽象方法,以之前IMessage接口为例,在这个接口里面发现只是提供欧冠有一个send()方法,除此之外没有任何的其他方法定义,所以这样的接口就被称为函数式接口,而只有函数式接口才可以被Lambda表达式所使用。
使用函数式接口注解
@FunctionalInterface // 函数式接口
interface IMessage{
public void send(String str);
}
public class JavaDemo{
public static void main(String args[]){
IMessage msg = (str)->{
System.out.println("发送消息"+str);
};
msg.send("www.mldn.cn");
}
}
`
对于Lambda表达式而言,提供有如下几种格式:
‒ 方法没有参数:()->{}
‒ 方法有参数:(参数,参数)->{}
‒ 如果现在只有一行语句返回:(参数,参数)->语句;
简化Lambda表达式
@FunctionalInterface // 函数式接口
interface IMath{
public int add(int x , int y);
}
public class JavaDemo{
public static void main(String args[]){
IMath msg = (t1,t2)->t1+t2;
System.out.println(msg.add(10,20));
}
}
利用Lambda表达式的确可以摆脱传统面向对象之中关于结构的限制,使得代码更加的简便