Supplier<T>和Consumer<T>

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

这2个java8的函数式接口,都是带@FunctionalInterface注解的。

Supplier<T>是提供者,方法是get,也就是直接在get的时候才真正的调用该方法。比如:
    @Test
    public void test(){
        Supplier<String> supplier = ()->getStudentCode();
        //其他逻辑
        //执行get方法的时候才执行getStudentCode方法
        String s = supplier.get();
        System.out.println(s);
    }

    private String getStudentCode(){
        return "11223334444";
    }
Consumer<T>是消费者,只有在执行accept方法的时候,才会执行。
    @Test
    public void test(){
        Consumer<String> consumer = (value) -> {
            StudentInfoDTO studentInfoByCode = getStudentInfoByCode(value);
            System.out.println(JsonUtils.toJson(studentInfoByCode));
        };
        consumer.accept("11223334444");
    }

    public StudentInfoDTO getStudentInfoByCode(String code) {
        StudentInfoDTO dto=new StudentInfoDTO();
        dto.setEmail("111111");
        dto.setMobile("44444444");
        dto.setIdCard(code);
        return dto;
    }

在平时的工作中,这2个还是很常用的,比如在redis存储的时候,就可以使用。还有我们常用的一些集合ArrayList、Stream等源码中也是常见的。

### 如何从 `Optional<DataCollection>` 提取数据 在 Java 中,`Optional<T>` 是一种容器类,用于表示可能为空的对象。为了安全地访问其中的内容并避免潜在的 NullPointerException,可以使用其内置的方法来处理逻辑。 以下是通过代码示例展示如何从 `Optional<DataCollection>` 获取 `DataCollection` 值的方式: #### 方法一:使用 `.orElseThrow()` 抛出异常 如果希望当 `Optional` 为空时抛出自定义异常,则可以通过 `.orElseThrow()` 实现。 ```java import java.util.Optional; public class Example { public static void main(String[] args) { Optional<DataCollection> optionalData = getData(); try { DataCollection data = optionalData.orElseThrow(() -> new IllegalStateException("No data available")); System.out.println(data); } catch (IllegalStateException e) { System.err.println(e.getMessage()); } } private static Optional<DataCollection> getData() { // 模拟返回 Optional 数据 return Optional.of(new DataCollection("Sample Data")); // 或者返回 Optional.empty() } } class DataCollection { private String value; public DataCollection(String value) { this.value = value; } @Override public String toString() { return "DataCollection{" + "value='" + value + '\'' + '}'; } } ``` 上述代码展示了如何利用 `.orElseThrow()` 来确保程序不会因空指针而崩溃[^1]。 --- #### 方法二:使用 `.ifPresent()` 执行特定操作 如果仅需在存在值的情况下执行某些操作而不关心其他场景,`.ifPresent(Consumer<? super T>)` 可能更合适。 ```java optionalData.ifPresent(data -> process(data)); private static void process(DataCollection data) { System.out.println("Processing: " + data.toString()); } ``` 这种方式适用于不需要显式捕获异常或提供默认行为的情形。 --- #### 方法三:使用 `.map()` 链式调用 对于复杂的数据转换需求,可以结合 `.map(Function)` 进行映射进一步处理。 ```java optionalData.map(DataCollection::getValue) .ifPresent(value -> System.out.println("Extracted Value: " + value)); // Assuming the following method exists in DataCollection: public String getValue() { return this.value; } ``` 这种方法特别适合于需要对嵌套对象属性进行提取的操作。 --- #### 方法四:使用 `.orElseGet(Supplier)` 设置默认值 如果希望为缺失的值指定一个替代方案,可以采用 `.orElseGet(Supplier)` 方法。 ```java DataCollection defaultData = new DataCollection("Default Data"); DataCollection result = optionalData.orElseGet(() -> defaultData); System.out.println(result); // 输出实际存在的值或者默认值 ``` 该方式允许灵活定义缺省情况下应返回的结果。 --- ### 总结 以上介绍了四种常见的从 `Optional<DataCollection>` 提取数据的技术手段。每种方法都有各自适用范围,在开发过程中可以根据具体业务需求选择最恰当的一个实现路径。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值