Supplier接口:

java.util.Supplier<T>接口包含一个无参的方法:T get()。

用来获取一个泛型参数指定类型的对象数据

public class Demo {
    public static void main(String[] args) {
        System.out.println(getString(()->"12341"));
    }
    public static String getString(Supplier<String>sup) {
        return sup.get();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

Supplier<T>接口被称之为生产型接口,指定接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据

练习:使用Supplier接口作为方法参数类型,通过Lambda表达式求出int数组中的最大值

public class Demo {
    public static void main(String[] args) {
        int[]arr={100,12,35};
        System.out.println(getMax(()->{int m=arr[0];
          for(int i=0;i<arr.length;i++){
              if(arr[i]>m){
                  m=arr[i];
              }
          }
          return m;
        }));
    }
    public static Integer getMax(Supplier<Integer>sup) {
        return sup.get();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.