1. Lambda语法的三种形式
- (参数) -> 单行语句
- (参数) -> {多行语句}
- (参数) -> 表达式
2. 注意
- 接口中使用,接口只定义一个接口方法
- 外部变量被lambda表达式引用,编译器会隐式的把其当成final来处理
3. 普通匿名内部类
// 函数式接口声明注解(只能定义一个方法)
@FunctionalInterface
interface IMessage {
void print();
}
public class LambdaDemo1 {
public static void main(String... args) {
fun(new IMessage() {
@Override
public void print() {
System.out.println("Hello World!"); // 核心代码就这一条
}
});
}
private static void fun(IMessage msg) {
msg.print();
}
}
4. Lambda表达式
@FunctionalInterface
interface IMessage2 {
void print();
}
public class LambdaDemo2 {
public static void main(String... args) {
fun(() -> System.out.println("Hello World!"));
}
private static void fun(IMessage2 msg) {
msg.print();
}
}
5. 带参的Lambda表达式
@FunctionalInterface
interface IMessage2 {
void print(String str);
}
public class LambdaDemo2 {
public static void main(String... args) {
// 首先要定义此处表达式里面需要接收变量,单行语句直接进行输出
fun((s) -> System.out.println(s));
}
private static void fun(IMessage2 msg) {
msg.print("Hello World");
}
}
6. 编写多行语句
@FunctionalInterface
interface IMessage2 {
void print(String str);
}
public class LambdaDemo2 {
public static void main(String... args) {
// 首先要定义此处表达式里面需要接收变量,单行语句直接进行输出
fun((s) -> {
s = s.toUpperCase();
System.out.println(s);
});
}
private static void fun(IMessage2 msg) {
msg.print("Hello World");
}
}
7. 编写一个表达式
@FunctionalInterface
interface IMessage2 {
int add(int x, int y);
}
public class LambdaDemo2 {
public static void main(String... args) {
fun((x, y) -> x + y);
}
private static void fun(IMessage2 msg) {
System.out.println(msg.add(10, 20));
}
}