Java基础(三十三)

Lambda表达式

背景:从JDK1.8开始为了简化使用者进行代码开发,专门提供有Lambda的支持,可以实现函数式编程(函数式编程比较著名的是haskell Scala),利用函数式编程可以避免面向对象编程之中的一些繁琐的处理问题。

1观察传统开发中的问题

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") ;
	}
} 

在这里插入图片描述

2下面利用Lambda表达式实现与之前完全一样的功能

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),只有一个抽象方法;

这样的借口被成为函数式接口,只有函数式接口才可以被Lambda表达式所使用。

3:使用函数式接口注解

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") ;
	}
} 

在这里插入图片描述

4定义没有参数的方法

@FunctionalInterface	// 函数式接口
interface IMessage {
	public void send() ;
}
public class JavaDemo {
	public static void main(String args[]) {
		IMessage msg = ()->{
			System.out.println("发送消息:www.mldn.cn") ;
		} ;
		msg.send() ;
	}
}

5:定义有参数的处理形式

@FunctionalInterface	// 函数式接口
interface IMath {
	public int add(int x,int y) ;
}
public class JavaDemo {
	public static void main(String args[]) {
		IMath math = (t1,t2)->{
			return t1 + t2 ;
		} ;
		System.out.println(math.add(10,20)) ;
	}
} 

6:简化Lambda表达式操作


@FunctionalInterface	// 函数式接口
interface IMath {
	public int add(int x,int y) ;
}
public class JavaDemo {
	public static void main(String args[]) {
		IMath math = (t1,t2)-> t1 + t2 ;
		System.out.println(math.add(10,20)) ;
	}
} 

猜你喜欢

转载自blog.csdn.net/qq_35649064/article/details/83833367