Lambda 表达式

本文详细介绍了Java8中引入的Lambda表达式,通过对比匿名内部类,展示了Lambda表达式如何简化函数式接口的使用。包括无返回值、单行代码及有返回值的Lambda表达式语法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java支持Lambda 表达式始于Java 8,它的出现简化了函数式接口匿名内部类的语法,其表达式语法如下:([参数1], [参数2], [参数3],… [参数n])->{代码块}
匿名内部类:

@FunctionalInterface
interface IComputer {
	void add(int a, int b);
	}
public class Test {
	public static void main(String[] args) {
		IComputer computer = new IComputer() {
			@Override
			public void add(int a, int b) {
				System.out.println(a + b);
				}
			};
			computer.add(1, 1);
		}
}

Lambda 表达式:

@FunctionalInterface
interface IComputer {
		void add(int a, int b);
	}
public class Test {
		public static void main(String[] args) {
			IComputer computer = (int a, int b)-> {
				System.out.println(a + b);
				};
			computer.add(1, 1);
	}
}	

如果方法没有返回值且只有一行代码,则Lambda表达式语法可以是这种形式:([参数1], [参数2], [参数3],… [参数n])->单行语句,如下例:

匿名内部类:

@FunctionalInterface
interface IMammal {
	void move(String name);
	}
public class Test {
	public static void main(String[] args) {
			IMammal whale = (name) -> {
					System.out.println(name+"正在移动......");
					};
	whale.move("鲸鱼");
	}
}

Lambda 表达式:

@FunctionalInterface
interface IMammal {
	void move(String name);
	}
public class Test {
	public static void main(String[] args) {
		IMammal whale = (name) -> System.out.println(name+"正在移动......");
		whale.move("鲸鱼");
		}
}		

如果方法有返回值且只有一行代码,则Lambda表达式语法可以是这种形式:([参数1], [参数2], [参数3],… [参数n])->表达式,如下例:

匿名内部类:

@FunctionalInterface
interface IComputer {
	int add(int a, int b);
	}
public class Test {
public static void main(String[] args) {
	IComputer computer = (a, b) -> {
		return a+b;
		};
	int result = computer.add(1,2);
	System.out.println(result);
	}
}		

Lambda 表达式:

@FunctionalInterface
interface IComputer {
	int add(int a, int b);
	}
public class Test {
	public static void main(String[] args) {
		IComputer computer = (a, b) -> a+b;
		int result = computer.add(1,2);
		System.out.println(result);
		}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值