Java 8 - Consumer example

Consumer is a functional interface that takes one Type T argument and has no return value.

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

}

Example 1 : Consumer

Consumers can be implemented as Lambda expressions. Passing arguments with the accept() call will do the implementation.

import java.util.function.Consumer;

public class ConsumerExample1 {

    public static void main(String[] args) {
        Consumer<String> consumer = s -> System.out.println(s.toUpperCase());

        consumer.accept("hello world");
    }
}

Output:

HELLO WORLD

Example 2 : Primitive Consumer

Java provides a Consumer class for primitive types. In addition to IntConsumer, there are DoubleConsumer and LongConsumer.

import java.util.function.IntConsumer;

public class ConsumerExample2 {

    public static void main(String[] args) {
        IntConsumer consumer = n -> System.out.println(n * 100);

        consumer.accept(5);

        consumer.accept(10);
    }
}

Output:

500
1000

Example 3 : List.forEach()

List.forEach() takes a Consumer as an argument.

You can print all items in the List using Consumer as follows.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerExample3 {

    public static void main(String[] args) {
        Consumer<String> consumer = s -> System.out.println(s.toUpperCase());

        List<String> list = Arrays.asList("apple", "kiwi", "orange");

        list.forEach(consumer);
    }
}

Output:

APPLE
KIWI
ORANGE

Example 4 : andThen()

andThen() is a chaining method that connects consumers.

When calling addNumber.andThen(printList).accept(fruits) in the code below, printList() is executed after printList(). The argument passed to both methods is fruits, and the same object is passed.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerExample4 {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "kiwi", "orange");

        Consumer<List<String>> addNumber = list -> {
            for (int i = 0; i < list.size(); i++) {
                list.set(i, (i + 1) + ". " + list.get(i));
            }
        };

        Consumer<List<String>> printList = list -> {
            for (String fruit : list) {
                System.out.println(fruit);
            }
        };

        addNumber.andThen(printList).accept(fruits);
    }
}

Output:

1. apple
2. kiwi
3. orange

Actually andThen() is implemented as below.

// Consumer.java
public interface Consumer<T> {
  ...
  default Consumer<T> andThen(Consumer<? super T> after) {
      Objects.requireNonNull(after);
      return (T t) -> { accept(t); after.accept(t); };
  }
}

Example 5 : Passing Consumer as a function argument (Higher Order Function)

You can define a function that takes a Consumer as an argument as follows.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerExample5 {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "kiwi", "orange");

        Consumer<String> printFruit = fruit -> System.out.println("I like " + fruit);

        forEach(fruits, printFruit);
    }

    static <T> void forEach(List<T> list, Consumer<T> consumer) {
        for (T t : list) {
            consumer.accept(t);
        }
    }

}

Output:

I like apple
I like kiwi
I like orange

References

codechachaCopyright ©2019 codechacha