o7planning

Java Consumer Tutorial with Examples

  1. Consumer
  2. Consumer + Method reference
  3. Consumer.andThen

1. Consumer

In Java 8, Consumer is a functional interface, representing an operator that accepts an input parameter and returns nothing.
Consumer
@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);

    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> {
            accept(t);
            after.accept(t);
        };
    }
}
Example:
ConsumerEx1.java
package org.o7planning.ex;

import java.util.function.Consumer;

public class ConsumerEx1 {
    
    public static void main(String[] args)  {

        // Create a Consumer object directly
        Consumer<String> greeter = name -> System.out.println("Hello " + name);
        
        greeter.accept("Tran");   // Hello Tran
    }
}
Expanding the above example, we use Consumer in Stream.forEach method.
// A method of Stream class
public void forEach(Consumer<? super T> action);
ConsumerEx2.java
package org.o7planning.ex;

import java.util.function.Consumer;
import java.util.stream.Stream;

public class ConsumerEx2 {
    
    public static void main(String[] args)  {

        // Create a Consumer object directly
        Consumer<String> greeter = name -> System.out.println("Hello " + name);  
        
        Stream<String> names = Stream.of("Tran", "Nguyen", "Pham");
        
        names.forEach(greeter);
    }
}
Output:
Hello Tran
Hello Nguyen
Hello Pham
Below is a list of the methods in the java.util package using Consumer:
Modifier and Type
Method and Description
void
ArrayList.forEach(Consumer<? super E> action)
void
Vector.forEach(Consumer<? super E> action)
default void
PrimitiveIterator.OfDouble.forEachRemaining(Consumer<? super Double> action)
default void
Spliterator.OfDouble.forEachRemaining(Consumer<? super Double> action)
default void
Iterator.forEachRemaining(Consumer<? super E> action)
default void
PrimitiveIterator.OfInt.forEachRemaining(Consumer<? super Integer> action)
default void
Spliterator.OfInt.forEachRemaining(Consumer<? super Integer> action)
default void
PrimitiveIterator.OfLong.forEachRemaining(Consumer<? super Long> action)
default void
Spliterator.OfLong.forEachRemaining(Consumer<? super Long> action)
default void
Spliterator.forEachRemaining(Consumer<? super T> action)
void
Optional.ifPresent(Consumer<? super T> consumer)
default boolean
Spliterator.OfDouble.tryAdvance(Consumer<? super Double> action)
default boolean
Spliterator.OfInt.tryAdvance(Consumer<? super Integer> action)
default boolean
Spliterator.OfLong.tryAdvance(Consumer<? super Long> action)
boolean
Spliterator.tryAdvance(Consumer<? super T> action)
See also: BiConsumer is a class similar to Consumer, the difference is that it accepts 2 parameters:

2. Consumer + Method reference

If a method has a single parameter and returns nothing, its reference can be considered a Consumer.
Example: System.out.println(param) method takes one parameter and returns nothing, then its reference System.out::println will be considered as a Consumer.
ConsumerEx5.java
package org.o7planning.ex;

import java.util.function.Consumer;

public class ConsumerEx5 {

    public static void main(String[] args) {

        myPrintln(System.out::println, "Hello World!");
    }
    
    public static <T> void myPrintln(Consumer<T> c, T t) {
         c.accept(t);
    }
}
Output:
Hello World!
Example:
ConsumerEx6.java
package org.o7planning.ex;

import java.util.stream.Stream;

public class ConsumerEx6 {

    public static void main(String[] args) {
        
        Stream<String> names = Stream.of("Tran", "Nguyen", "Pham");
        
        // Call method: Stream.forEach(Consumer)
        names.forEach(System.out::println);
    }
    
}
Output:
Tran
Nguyen
Pham

3. Consumer.andThen

andThen(after) method returns an associated Consumer. First, the current Consumer will be called then after will be called. If an error occurs in one of the two steps above, the error will be passed to the caller. If an error occurs at the current Consumer then after is ignored.
Consumer
default Consumer<T> andThen(Consumer<? super T> after) {
    Objects.requireNonNull(after);
    return (T t) -> {
       accept(t);
       after.accept(t);
    };
}
Example:
ConsumerEx3.java
package org.o7planning.ex;

import java.util.function.Consumer;

public class ConsumerEx3 {
    
    public static void main(String[] args)  {
        
        Consumer<String> c = text -> System.out.println(text.toLowerCase());   
         
        c.andThen(c).accept("Hello");
    }
}
The result is that the word "hello" was printed out twice.
hello
hello
Example:
ConsumerEx4.java
package org.o7planning.ex;

import java.util.function.Consumer;

public class ConsumerEx4 {

    public static void main(String[] args) {

        Consumer<UserAccount> c1 = test -> test.auth();

        Consumer<UserAccount> c2 = test -> test.welcome();

        UserAccount user = new UserAccount("tran", "123");

        try {
            c1.andThen(c2).accept(user);
        } catch (Exception e) {

        }
    }

    public static class UserAccount {
        private String userName;
        private String password;

        public UserAccount(String userName, String password) {
            this.userName = userName;
            this.password = password;
        }

        public void auth() {
            if ("123".equals(password)) {
                System.out.println("Valid Account!");
            } else {
                throw new RuntimeException("Invalid Password");
            }
        }

        public void welcome() {
            System.out.println("Welcome! " + this.userName);
        }
    }
}
Output:
Valid Account!
Welcome! tran

Java Basic

Show More