Java BiConsumer源码总结 BiConsumer接口注释翻译和解析中英文对照版

(164) 2024-03-20 11:01:01

BiConsumer函数式接口源码重点
1.BiConsume是一个函数式接口,里面只有一个需要实现的方法是 void accept(T t, U u),表示一个接受两个输入参数但不返回结果的操作,通常用于处理键值对,key是一个参数,值是一个参数,BiConsumer函数式接口与Consumer函数式接口的区别是Consumer的void accept(T t),表示一个接受单个输入参数但不返回结果的操作,Consumer源码可以看我这篇文章 Consumer

2.BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after)用于拼接多个BiConsumer的accept(T t, U u)方法,按顺序执行操作,如果前面的操作抛出异常,则后面的操作不会执行

3.Consumer接口方法

方法名 作用
void accept(T t, U u) 表示一个接受两个输入参数但不返回结果的操作
default BiConsumer andThen(BiConsumer after) 返回一个组合的新BiConsumer,在新的BiConsumer会先对两个参数此BiConsumer的accept操作再执行after中的accept操作

BiConsumer函数式接口源码

package java.util.function;

import java.util.Objects;

/**
 * Represents an operation that accepts two input arguments and returns no
 * result.  This is the two-arity specialization of {@link Consumer}.
 * Unlike most other functional interfaces, {@code BiConsumer} is expected
 * to operate via side-effects.
 * 表示接受两个输入参数但不返回结果的操作。这是Consumer的两个算术特化。
 * 与大多数其他功能接口不同,BiConsumer预期通过副作用运行。
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object, Object)}.
 * 这是一个函数接口,其函数方法是accept(Object, Object)
 * 
 * @param <T> the type of the first argument to the operation
 * @param <U> the type of the second argument to the operation
 *
 * @see Consumer
 * @since 1.8
 */
@FunctionalInterface
public interface BiConsumer<T, U> {

    /**
     * Performs this operation on the given arguments.
     * 对给定参数执行此操作。
     *
     * @param t the first input argument
     * @param u the second input argument
     */
    void accept(T t, U u);

    /**
     * Returns a composed {@code BiConsumer} 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.
     * 返回一个组合的BiConsumer,它依次执行此操作和after操作。
     * 如果执行任何一个操作都会引发异常,则会将异常转发给组合操作的调用方。
     * 如果执行此操作引发异常,则不会执行after操作。
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code BiConsumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
        Objects.requireNonNull(after);

        return (l, r) -> {
            accept(l, r);
            after.accept(l, r);
        };
    }
}

THE END

发表回复