目录一、举例说明1、无参无返回1.1 定义一个接口1.2接口实现类1.3 测试类2、有参无返回代码示例3、有参有返回二、简单事项1、省略模式2、注意事项三、Lambda表达式和匿名内部类的区别1、所需类型不同:2、使用限制不同:3、实现原理
标准格式:
三要素:形式参数 箭头 代码块
格式:(形式参数)->{代码块}
形式参数:如果多个参数用逗号隔开,无参留空
->:英文中划线和大于号组成
代码块:具体要做的事
使用前提:
有一个接口
接口中有且仅有一个抽象方法
public interface Eatable {
void eat();
}
public class EatableImpl implements Eatable{
@Override
public void eat() {
System.out.println("一天一苹果");
}
}
public class EatableDemo {
public static void main(String[] args) {
//主方法调用useEatable
Eatable e = new EatableImpl();
useEatable(e);
//匿名内部类
useEatable(new Eatable() {
@Override
public void eat() {
System.out.println("一天一苹果");
}
});
//lambda表达式
useEatable(() -> {
System.out.println("一天一苹果");
});
}
private static void useEatable(Eatable e){
e.eat();
}
}
public interface Eatable {
void eat(String name);
}
public class EatDemo {
public static void main(String[] args) {
useEat((String name) -> {
System.out.println(name);
System.out.println("输出的啥");
});
}
private static void useEat(Eatable e){
e.eat("苹果");
}
}
public interface Addable {
int add(int x,int y);
}
1.
2.
3.
public class AddableDemo {
public static void main(String[] args) {
useAddable( (int x,int y ) -> {
return x+y;
});
}
private static void useAddable(Addable a){
int sum = a.add(5, 7);
System.out.println(sum);
}
}
到此这篇关于Java中Lambda表达式基础及使用的文章就介绍到这了,更多相关Java中Lambda表达式内容请搜索编程界以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程界!
--结束END--
本文标题: Java中Lambda表达式基础及使用
本文链接: https://www.lsjlt.com/news/82.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2023-09-27
2023-09-26
2023-09-26
2023-09-26
2023-09-26
2023-09-25
2023-09-25
2023-09-25
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0