Consumer
Consumer接口表示一个消费者,它接受一个泛型类型参数T
,但不返回任何结果。
java
@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); };
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
JDK中的使用场景
- java.util.Iterator#forEachRemaining
- java.lang.Iterable#forEach
- java.util.stream.Stream
- java.util.Spliterator
- java.util.concurrent.CompletableFuture
- java.util.Optional#ifPresent
扩展接口
- IntConsumer:只接受
int
参数的Consumer - LongConsumer:只接受
long
参数的Consumer - DoubleConsumer:只接受
double
参数的Consumer - BiConsumer:接受两个参数的Consumer
- ObjIntConsumer:接受一个泛型、一个
int
类型参数的BiConsumer - ObjLongConsumer:接受一个泛型、一个
long
类型参数的BiConsumer - ObjDoubleConsumer:接受一个泛型、一个
double
类型参数的BiConsumer