Java 常用函数式接口之 Supplier接口

文章介绍了Java的Supplier接口,它是一个函数式接口,只有一个无参方法Tget()。通过示例展示了如何使用Lambda表达式与Supplier接口结合,获取并拼接字符串,以及如何利用Supplier找到int数组的最大值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

>>> JDK提供了大量常用的函数式接口以丰富Lambda的典型使用场景,它们主要在 java.util.function 包中被提供。本文是最简单的Supplier接口及使用示例。

 

概述

// Supplier接口源码


@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

java.util.function.Supplier 接口仅包含一个无参的方法: T get() 。用来获取一个泛型参数指定类型的对象数据。由于这是一个函数式接口,这也就意味着对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。如:

import java.util.function.Supplier;

public class Demo01Supplier {
    public static void main(String[] args) {
        String msgA = "Hello ";
        String msgB = "World ";
        System.out.println(
                getString(
                        () -> msgA + msgB
                )
        );
    }

    private static String getString(Supplier<String> stringSupplier) {
        return stringSupplier.get();
    }
}

控制台输出:

Hello World 

练习:求数组元素最大值

使用 Supplier 接口作为方法参数类型,通过Lambda表达式求出int数组中的最大值。接口的泛型使用 java.lang.Integer 类。

import java.util.function.Supplier;

public class DemoNumberMax {
    public static void main(String[] args) {
        int[] numbers = {100, 200, 300, 400, 500, -600, -700, -800, -900, -1000};
        int numberMax = arrayMax(
                () -> {
                    int max = numbers[0];
                    for (int number : numbers) {
                        if (max < number) {
                            max = number;
                        }
                    }
                    return max;
                }
        );
        System.out.println("数组中的最大值为:" + numberMax);
    }

    /**
     * 获取一个泛型参数指定类型的对象数据
     * @param integerSupplier 方法的参数为Supplier,泛型使用Integer
     * @return 指定类型的对象数据
     */
    public static Integer arrayMax(Supplier<Integer> integerSupplier) {
        return integerSupplier.get();
    }
}

控制台输出:

数组中的最大值为:500

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值