Consumer<String> first = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("执行first: "+s);
}
};
Consumer<String> second = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("执行second: "+s);
}
};
// 最终效果是一个接一个依次执行
Consumer<String> compose = first.andThen(second);
// 执行first: 123
// 执行second: 123
compose.accept("123");
2、源码翻译
涉及到一个函数的副作用:side-effects
package java.util.function;
import java.util.Objects;
/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@code Consumer} is expected
* to operate via side-effects.
* 表示接受单个输入参数并且不返回结果的操作。 与大多数其他函数接口不同, Consumer预计将通过副作用进行操作。
* side-effects的理解:
* 函数的主要作用,y = 2x 函数的返回值是返回一个数的2倍,对每个自变量 x 计算出一个相对应的因变量 y。
* 函数的副作用可能会比首要功能更重要。例如有 write() 这个函数,把一些字符写到一个文件里,传回true/false表示是否写成功,甚至不回传。
* 这里明显可以看出,我们叫这个函数,主要还是希望它能把东西写到文件里的。
* 可惜从数学的角度来讲,函数的首要功能永远都是返回值,所以这里“写文件”操作也被定义为“副作用”。
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #accept(Object)}.
* 这是一个functional interface的功能方法是accept(Object) 。
*
* @param <T> the type of the input to the operation
*
* @since 1.8
*/
@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.
* 返回一个组合的Consumer , Consumer执行该操作,后跟after操作。
* 如果执行任一操作会抛出异常,它将被转发到组合操作的调用者。 如果执行此操作抛出一个异常, after操作将不被执行。
*
* @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
* 一个组合的 Consumer按顺序执行该操作,后跟 after操作
* @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); };
}
}