0
点赞
收藏
分享

微信扫一扫

lambda表达式入门例子


说是函数式接口。其实也可以理解为匿名内部类。
最简单的例子:

@FunctionalInterface  // 表示函数式接口,编译的时候会强制校验
public interface Animal {
void show();

public static void main(String[] args) {
Animal person=()-> System.out.println("2 tiao tui"); //人有2条腿
person.show();
Animal pig=()-> System.out.println("4 tiao tui"); // 猪有四条腿
pig.show();
}
}

带参数的例子:

public interface Count {
int add(int a,int b);

public static void main(String[] args) {
Count count=(a,b)->a+b; // 如果只有一个参数,小括号也不用加
System.out.println(count.add(2,3));
}
}

省略写法:

@FunctionalInterface
public interface Animal {
void show(String name);

public static void main(String[] args) {
Animal person=(name)-> System.out.println("name");
person.show("ren");
Animal pig= System.out::println; //入参和方法中调用的是同一对象的时候,连入参也可以省略了
pig.show("zhu");
}
}

省略写法构造对象:
Acount 代码:

@Data
public class Acount {
private String username;
private String password;

public Acount(String username, String password) {
this.username = username;
this.password = password;
}
}

Manager代码:

public interface Manager {
Object create(String username,String password);

public static void main(String[] args) {
Manager acount=(username,password)->new Acount(username,password);
System.out.println(acount);
Manager acount2=Acount::new; // 入参的所有参数给方法体,那么可以简写
System.out.println(acount2);
}
}


举报

相关推荐

0 条评论