Javase Lambda表达式
体验简单Lambda表达式
LambdaDemo
package com.itheima581;
public class LambdaDemo {
public static void main(String[] args) {
// 3种方式实现线程
// 1-1通过编写Runnable实现类方法
Thread t = new Thread(new ThreadDemo());
t.start();
// 1-2通过匿名内部类
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程方式2启动");
}
}).start();
// 1-3通过Lambda发送
new Thread(()->{
System.out.println("线程方式3启动");
}).start();
}
}
ThreadDemo实现类
package com.itheima581;
public class ThreadDemo implements Runnable{
@Override
public void run(){
System.out.println("线程方式1启动");
}
}
表达式格式
(形式参数) -> {代码块}
Lambda中的“省略模式”
1.参数只有一个,括号可以省略;例:s -> {}
2. 如果代码块只有一句,大括号与分号可以省略;例:s -> 代码块
3. 参数类型可以省略;例:(int s) - > 代码块 == (s) -> 代码块
4. 如果有返回类型,return可以省略;前提是只有一句代码块
package com.itheima581;
interface Addable {
int add(int x,int y);
}
interface Animal {
void eat(String food);
}
public class LambdaDemo1 {
public static void main(String[] args) {
// 省略括号,参数类型
userAnimal(s -> {
System.out.println(s);
});
// 省略大括号,分号,return
userAdd((x, y) -> x + y);
}
public static void userAnimal(Animal animal) {
animal.eat("鱼");
}
public static void userAdd(Addable a) {
int sum = a.add(20, 30);
System.out.println(sum);
}
}
注意事项
- 必须有接口,接口有且仅有一个方法
- 上下文环境
与匿名内部类的区别
- Lambda只能实现接口,匿名内部类还可以实现抽象类与具体类