Java 函数式编程
![](https://i-blog.csdnimg.cn/direct/1f965f4175a14e9698568055eb9f6772.png)
12.1. Supplier 供应型的接口
Supplier<String> supplier = () -> "hello, world";
String result = supplier.get();
System.out.println(result);
Supplier stringSupplier = () -> new String("Hi Neo");
String string = stringSupplier.get();
System.out.println(string);
Supplier<LocalDateTime> currentTime = () -> LocalDateTime.now();
LocalDateTime now = currentTime.get(); // 计算当前时间
Optional<String> optional = Optional.ofNullable("hello");
String orElseGet = optional.orElseGet(() -> "world");
Supplier userSupplier= () -> new User(1,"netkiller");
User user=userSupplier.get();
System.out.println(user.getName());
package cn.netkiller.test;
import java.util.function.Supplier;
public class TestSupplier {
private final int age = 24;
TestSupplier() {
System.out.println(age);
}
public static void main(String[] args) {
Supplier<TestSupplier> supplier = TestSupplier::new;
//调用get()方法,此时会调用对象的构造方法,即获得到真正对象
supplier.get();
System.out.println(supplier.get().test());
TestSupplier test = supplier.get();
System.out.println(test.test());
}
private String test() {
return "Helloworld!!!";
}
}
package cn.netkiller.test;
import java.util.function.Supplier;
public class TestSupplier {
private final int age = 24;
private final String name;
TestSupplier(String name) {
this.name = name;
// System.out.println(name);
}
public static void main(String[] args) {
Supplier<String> stringSupplier = () -> {
return "test1";