就像名字一样,它只是一个消费者,它的任务很简单,就是消费

    Consumer的Function method是accept。

    1. /**
    2. * Performs this operation on the given argument.
    3. *
    4. * @param t the input argument
    5. */
    6. void accept(T t);

    andThen方法接受一个Consumer对值进行两次消费 ;)

    1. /**
    2. * Returns a composed {@code Consumer} that performs, in sequence, this
    3. * operation followed by the {@code after} operation. If performing either
    4. * operation throws an exception, it is relayed to the caller of the
    5. * composed operation. If performing this operation throws an exception,
    6. * the {@code after} operation will not be performed.
    7. *
    8. * @param after the operation to perform after this operation
    9. * @return a composed {@code Consumer} that performs in sequence this
    10. * operation followed by the {@code after} operation
    11. * @throws NullPointerException if {@code after} is null
    12. */
    13. default Consumer<T> andThen(Consumer<? super T> after) {
    14. Objects.requireNonNull(after);
    15. return (T t) -> { accept(t); after.accept(t); };
    16. }
    1. @Test
    2. public void consumerFi () {
    3. List<String> stringList = new ArrayList<>();
    4. Consumer<String> consumer = new Consumer<String>() {
    5. @Override
    6. public void accept (String o) {
    7. stringList.add(o);
    8. }
    9. };
    10. List<String> anotherStringList = Arrays.asList("str1", "str2", "str3", "str4", "str5");
    11. anotherStringList.forEach(consumer);
    12. stringList.forEach(System.out::println);
    13. System.out.println(":3########################");
    14. stringList.clear();
    15. anotherStringList.forEach(consumer.andThen(new Consumer<String>() {
    16. @Override
    17. public void accept (String s) {
    18. stringList.removeIf(new Predicate<String>() {
    19. @Override
    20. public boolean test (String s) {
    21. return s.equals("str3");
    22. }
    23. });
    24. }
    25. }));
    26. stringList.forEach(System.out::println);
    27. }

    输出:

    1. str1
    2. str2
    3. str3
    4. str4
    5. str5
    6. :3########################
    7. str1
    8. str2
    9. str4
    10. str5

    Consumer在流中的应用:

    • Stream中的peek
    • Stream中的forEach
    • Stream中的forEachOrdered

    等…

    Consumer在非流中的应用:

    • Iterator中的forEachRemaining
    • Iterable中的forEach

    等…