就像名字一样,他它只是一个消费者,他它的任务很简单,就是消费。
Consumer的Function method是accept。
/*** Performs this operation on the given argument.** @param t the input argument*/void accept(T t);
andThen方法接受一个Consumer对值进行两次消费 ;)
/*** 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); };}
@Testpublic void consumerFi () {List<String> stringList = new ArrayList<>();Consumer<String> consumer = new Consumer<String>() {@Overridepublic void accept (String o) {stringList.add(o);}};List<String> anotherStringList = Arrays.asList("str1", "str2", "str3", "str4", "str5");anotherStringList.forEach(consumer);stringList.forEach(System.out::println);System.out.println(":3########################");stringList.clear();anotherStringList.forEach(consumer.andThen(new Consumer<String>() {@Overridepublic void accept (String s) {stringList.removeIf(new Predicate<String>() {@Overridepublic boolean test (String s) {return s.equals("str3");}});}}));stringList.forEach(System.out::println);}
输出:
str1str2str3str4str5:3########################str1str2str4str5
Consumer在流中的应用:
- Stream中的peek
- Stream中的forEach
- Stream中的forEachOrdered
等…
Consumer在非流中的应用:
- Iterator中的forEachRemaining
- Iterable中的forEach
等…
