> 文章列表 > 常用的函数式接口——Supplier

常用的函数式接口——Supplier

常用的函数式接口——Supplier

java 8在java.util.function包下预定义了大量的函数式接口供我们使用

我们重点来学习下面的4个接口

        Supplier接口

        Consumer接口

        Predicate接口

        Function接口

Supplier<T>:包含一个无参的方法

        T get():获得结果

        该方法不需要参数,它会按照某种实现逻辑(由Lambda表达式实现)返回一个数据

        Supplier<T>接口也被称为生产型接口,如果我们指定了接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据供我们使用

package com.aynu23;//    Supplier<T>:包含一个无参的方法
//            T get():获得结果
//            该方法不需要参数,它会按照某种实现逻辑(由Lambda表达式实现)返回一个数据
//            Supplier<T>接口也被称为生产型接口,如果我们指定了接口的泛型是什么类型,那么接口中的get方法就会生产什么类型的数据供我们使用import java.util.function.Supplier;public class SupplierDemo {public static void main(String[] args) {
//        String s= getString(() ->{
//           return "林青霞";
//        });String s= getString(() ->"林青霞");System.out.println(s);Integer i = getInteger(() -> 30);//         getInteger(() -> 30);System.out.println(i);}//定义一个方法,返回一个字符串数据private static Integer getInteger(Supplier<Integer> sup){return sup.get();}private static String getString(Supplier<String> sup){return sup.get();}
}

林青霞
30 


 练习:

        定义一个类(SupplierTest),在类中提供两个方法

        一个方法是:int getMax(supplier<Integer> sup) 用于返回一个int数组中的最大值

        一个方法是主方法,在主方法中调用getMax方法

package com.aynu23;import java.util.function.Supplier;//    练习:
//
//         定义一个类(SupplierTest),在类中提供两个方法
//
//         一个方法是:int getMax(supplier<Integer> sup) 用于返回一个int数组中的最大值
//
//         一个方法是主方法,在主方法中调用getMax方法public class SupplierTest {public static void main(String[] args) {//定义一个int数组int[] arr = {19, 50, 28, 37, 46};int x=getMax(()->{int max=arr[0];for (int i=1;i<arr.length;i++){if (arr[i]>max){max=arr[i];}}return max;});System.out.println(x);}private static int getMax(Supplier<Integer> sup) {return sup.get();}
}

50