Lambda表达式
Lambda表达式
java普通函数的组成部分由:返回值,方法名,参数列表,方法体
int add(int a, int b){
return a + b;
}
Lambda表达式的函数,只有参数列表和方法体
( 参数列表 )-> { 方法体 }
():用来描述参数列表
{ } :用来描述方法体
-> :Lambda运算符,可以叫做箭头符号,或者goes to
public class Lambda {
public static void main(String[] args) {
If1 if1 = () -> {
System.out.println("无返回值、无参数");
};
if1.test();
If2 if2 = (int a) -> {
System.out.println("无返回值,单个参数 a=" + a);
};
if2.test(1);
If3 if3 = (int a, int b) -> {
System.out.println("无返回值,多个参数 a+b=" + (a + b));
};
if3.test(1, 2);
If4 if4 = () -> {
return 4;
};
System.out.println("有返回值、无参数 " + if4.test());
If5 if5 = (int a) -> {
return a;
};
System.out.println("有返回值,单个参数 a=" + if5.test(1));
If6 if6 = (int a, int b) -> {
return a + b;
};
System.out.println("有返回值,多个参数 a+b=" + if6.test(1, 2));
}
interface If1 {
void test();
}
interface If2 {
void test(int a);
}
interface If3 {
void test(int a, int b);
}
interface If4 {
int test();
}
interface If5 {
int test(int a);
}
interface If6 {
int test(int a, int b);
}
}
Lambda表达式精简语法
- 参数类型可以省略
- 假如只有一个参数,()可以省略(没有参数不能省略)
- 如果方法体只有一条语句,{}大括号可以省略
- 如果方法体中唯一的语句是return返回语句,那胜率大括号的同时return也要省略
package com.example.demo.lambda;
public class simplifyLambda {
public static void main(String[] args) {
Lambda.If1 if1 = () -> System.out.println("无返回值、无参数");
if1.test();
Lambda.If2 if2 = a -> System.out.println("无返回值,单个参数 a=" + a);
if2.test(1);
Lambda.If3 if3 = (a, b) -> System.out.println("无返回值,多个参数 a+b=" + (a + b));
if3.test(1, 2);
Lambda.If4 if4 = () -> 4;
System.out.println("有返回值、无参数 " + if4.test());
Lambda.If5 if5 = a -> a;
System.out.println("有返回值,单个参数 a=" + if5.test(1));
Lambda.If6 if6 = (a, b) -> a + b;
System.out.println("有返回值,多个参数 a+b=" + if6.test(1, 2));
}
interface If1 {
void test();
}
interface If2 {
void test(int a);
}
interface If3 {
void test(int a, int b);
}
interface If4 {
int test();
}
interface If5 {
int test(int a);
}
interface If6 {
int test(int a, int b);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!