Java8新特性,来源于数学中的λ[l?:md?]演算
是一套关于函数(f(x))定义、输入量、输出量的计算方案
package tech.flygo.lambda.demo1;
/**
* @description: 用户类
* @author: flygo
* @time: 2023/5/7 22:59
*/
public class User {
private String name;
private int age;
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" + "name='" + name + '\'' + ", age=" + age + '}';
}
}
package tech.flygo.lambda.demo1;
/**
* @description: 工程接口
* @author: flygo
* @time: 2023/5/7 22:58
*/
public interface Factory {
Object getObject();
}
package tech.flygo.lambda.demo1;
/**
* @description: 接口实现类
* @author: flygo
* @time: 2023/5/7 22:59
*/
public class SubClass implements Factory {
@Override
public Object getObject() {
return new User();
}
}
package tech.flygo.lambda.demo1;
/**
* @description: Lambda测试类
* @author: flygo
* @time: 2023/5/7 23:01
*/
public class LambdaTest {
public static void main(String[] args) {
// 1、子类实现接口
Factory factory = new SubClass(); // 多态
User user1 = (User) factory.getObject();
System.out.println(user1);
// 2、匿名内部类
factory =
new Factory() {
@Override
public Object getObject() {
return new User("张三", 18);
}
};
User user2 = (User) factory.getObject();
System.out.println(user2);
// 3、Lambda表达式
factory =
() -> {
return new User("李四", 20);
};
User user3 = (User) factory.getObject();
System.out.println(user3);
// 4、Lambda作为参数进行传递
User user4 =
getUserFromFactory(
() -> {
return new User("王五", 22);
},
User.class.getSimpleName());
System.out.println(user4);
// 5、Lambda作为函数返回值
factory = getFactory();
System.out.println(factory.getObject());
}
public static User getUserFromFactory(Factory factory, String beanName) {
Object object = factory.getObject();
if (object != null && object.getClass().getSimpleName().equals(beanName)) {
return (User) object;
}
return null;
}
public static Factory getFactory() {
return () -> {
return new User("赵六", 24);
};
}
}
// 3、Lambda表达式
factory =
() -> {
return new User("李四", 20);
};
User user3 = (User) factory.getObject();
System.out.println(user3);
// 4、Lambda作为参数进行传递
User user4 =
getUserFromFactory(
() -> {
return new User("王五", 22);
},
User.class.getSimpleName());
System.out.println(user4);
......
public static User getUserFromFactory(Factory factory, String beanName) {
Object object = factory.getObject();
if (object != null && object.getClass().getSimpleName().equals(beanName)) {
return (User) object;
}
return null;
}
// 5、Lambda作为函数返回值
factory = getFactory();
System.out.println(factory.getObject());
......
public static Factory getFactory() {
return () -> {
return new User("赵六", 24);
};
}