在Java中如何使用lambda表达式中的Supplier <T>接口?

Supplier<T>接口是一个预定义的接口,表示结果的提供者。它是使用lambda表达式、方法引用或默认构造函数实例化的。Supplier接口的函数方法是get()方法。此接口属于java.util.function函数接口。

语法

@FunctionalInterface
public interface Supplier<T>

在下面的程序中,我们可以在lambda表达式中使用Supplier接口。因为lambda()只返回一个参数为空的表达式,所以它不接受任何参数。

示例

import java.util.*;
import java.util.function.*;

public class SupplierTest {
   public static void main(String args[]) {
      Supplier<String> supplier1 = () -> "Nhooo";   // lambda表达式   
      System.out.println(supplier1.get());

      Supplier<Integer> supplier2 = () -> 7;    // lambda表达式
      System.out.println(supplier2.get());

      Person p = new Person("Raja");
      Person p1 = get(() -> p);
      Person p2 = get(() -> p);
      System.out.println(p1.equals(p2));
   }
   public static Person get(Supplier<Person> supplier) {
      return supplier.get();
   }
}
// Person 类
class Person {
   public Person(String name) {
      System.out.println(name);
   }
}

输出结果

Nhooo
7
Raja
true