首先要知道lambda表达式的使用前提是
1.接口为函数式接口即接口只有一个方法
2.如果有多个参数,可以去掉参数类型,要去掉就都去掉
- 先写一个最普通的
public class first {
public static void main(String[] args) {
eat i = new iEat();
i.eat();
}
}
interface eat{
void eat();
}
//class iEat就是内部类
class iEat implements eat{
@Override
public void eat() {
System.out.println("我吃饭");
}
}
静态内部类
*/
public class first {
//static class iEat是静态内部类
static class iEat implements eat {
@Override
public void eat() {
System.out.println("我吃饭");
}
public static void main(String[] args) {
eat i = new iEat();
i.eat();
}
}
interface eat {
void eat();
}
}
匿名内部类
public class first {
public static void main(String[] args) {
//new Ieat()是匿名内部类
Ieat i =new Ieat() {
@Override
public void eat(int a) {
System.out.println("我吃饭"+a);
}
};
i.eat(2);
}
interface Ieat {
void eat(int a);
}
}
lambda表达式推导
public class first {
public static void main(String[] args) {
Ieat i =(int a)-> {
System.out.println("我吃饭"+a);
};
i.eat(2);
}
interface Ieat {
void eat(int a);
}
}
实例
上下是等价的
Function function = new Function<String,String>(){
@Override
public String apply (String str){
return str;
}
};
Function function1 = (str)->{return str;};