Java Consumer Example
February 23, 2020
Java Consumer
interface is from java.util.function
package introduced in Java 8. The Consumer
is a functional interface used as assignment target for a lambda expression or method reference. The Consumer
functional interface is an operation that accepts a single argument and returns nothing. The functional method of Consumer
is accept(T t)
.
The
Consumer
has following methods.
1. accept : This is the functional method of
Consumer
functional interface. The accept
method performs this operation on the given argument.
2. andThen : This method returns a composed
Consumer
that performs this operation followed by the given operation.
Contents
Functional Method: accept
Find the functional method of Consumer
functional interface.
void accept(T t)
ConsumerAccept.java
import java.util.function.Consumer; public class ConsumerAccept { public static void main(String[] args) { Consumer<String> nameConsumer = s -> System.out.println(s); nameConsumer.accept("Mahesh"); nameConsumer.accept("Krishna"); } }
Mahesh Krishna
Creating Consumer with Lambda Expression
The JavaConsumer
can be created using lambda expression. Find the examples.
Example-1: We will create two
Consumer
here in our example using lambda expression.
One for adding number to list, if number is odd then we will add into a list with odd numbers and if number is even then we will add it into another list with even numbers.
We will create another
Consumer
that will display the list data.
ConsumerLambda1.java
import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class ConsumerLambda1 { public static void main(String[] args) { List<Integer> oddList = new ArrayList<>(); List<Integer> evenList = new ArrayList<>(); Consumer<Integer> storeNumber = n -> { if (n % 2 == 0) { evenList.add(n); } else { oddList.add(n); } }; Consumer<List<Integer>> printList = list -> list.forEach(n -> System.out.println(n)); storeNumber.accept(10); storeNumber.accept(15); storeNumber.accept(25); storeNumber.accept(30); System.out.println("--- Odd number ---"); printList.accept(oddList); System.out.println("--- Even number ---"); printList.accept(evenList); } }
--- Odd number --- 15 25 --- Even number --- 10 30
Consumer
using lambda expression that will decide and display data for a citizen whether that person can vote or not in election.
ConsumerLambda2.java
import java.util.function.Consumer; public class ConsumerLambda2 { public static void main(String[] args) { Consumer<Citizen> electionConsumer = c -> { if (c.getAge() < 18) { System.out.println(c.getName() + " is not eligible to vote."); } else { System.out.println(c.getName() + " can vote."); } }; electionConsumer.accept(new Citizen("Ritesh", 15)); electionConsumer.accept(new Citizen("Shreya", 20)); } } class Citizen { private String name; private int age; public Citizen(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
Ritesh is not eligible to vote. Shreya can vote.
Creating Consumer with Method Reference
The JavaConsumer
can be created using method reference.
In our example we have a utility class with two methods out of which one method will replace the value in map and second method displays the map data. We will create
Consumer
using method reference. Find the example.
ConsumerMethodRef.java
import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; public class ConsumerMethodRef { public static void main(String[] args) { Map<Integer, String> persons = new HashMap<Integer, String>(); persons.put(101, "Mahesh"); persons.put(102, "Krishna"); Consumer<Map<Integer, String>> updatePersons = Utility::updateData; Consumer<Map<Integer, String>> displayPersons = Utility::displayData; updatePersons.accept(persons); displayPersons.accept(persons); } } class Utility { static void updateData(Map<Integer, String> persons) { persons.replaceAll((k, v) -> "Shree ".concat(v)); } static void displayData(Map<Integer, String> persons) { for (Map.Entry<Integer, String> entry : persons.entrySet()) { System.out.println(entry.getKey() + " - " + entry.getValue()); } } }
101 - Shree Mahesh 102 - Shree Krishna
Using andThen
Method
Find the andThen
method declaration from Java doc.
default Consumer<T> andThen(Consumer<? super T> after)
1. This method returns a composed
Consumer
that performs this operation followed by the after
operation.
2. If there is exception either in this or
after
operation, it is relayed to the composed operation.
3. If this operation throws exception, the
after
operation will not be performed.
Example-1:
We have two
Consumer
in our example. First squareConsumer will execute and then printConsumer will execute.
ConsumerAndThen1.java
import java.util.Arrays; import java.util.List; import java.util.function.Consumer; public class ConsumerAndThen1 { public static void main(String[] args) { List<Integer> numList = Arrays.asList(3, 4, 5, 6); Consumer<List<Integer>> squareConsumer = list -> { for (int i = 0; i < list.size(); i++) { list.set(i, list.get(i) * list.get(i)); } }; Consumer<List<Integer>> printConsumer = list -> list.forEach(n -> System.out.println(n)); squareConsumer.andThen(printConsumer).accept(numList); } }
9 16 25 36
Example-2: Find one more example of
andThen
method. Here we are using andThen
multiple times. First oddNumConsumer will execute, then evenNumConsumer will execute and then taskFinishConsumer will execute.
ConsumerAndThen2.java
import java.util.Arrays; import java.util.List; import java.util.function.Consumer; public class ConsumerAndThen2 { public static void main(String[] args) { List<Integer> list = Arrays.asList(12, 13, 14, 15, 16, 17); Consumer<List<Integer>> oddNumConsumer = MyNumber::printOddNum; Consumer<List<Integer>> evenNumConsumer = MyNumber::printEvenNum; Consumer<List<Integer>> taskFinishConsumer = MyNumber::taskFinishMsg; oddNumConsumer.andThen(evenNumConsumer).andThen(taskFinishConsumer).accept(list); } } class MyNumber { static void printOddNum(List<Integer> myNumbers) { System.out.println("--- odd numbers ---"); myNumbers.forEach(n -> { if (n % 2 == 1) { System.out.print(n + " "); } }); } static void printEvenNum(List<Integer> myNumbers) { System.out.println("\n--- even numbers ---"); myNumbers.forEach(n -> { if (n % 2 == 0) { System.out.print(n + " "); } }); } static void taskFinishMsg(List<Integer> myNumbers) { System.out.println("\nTotal " + myNumbers.size() + " number processed."); } }
--- odd numbers --- 13 15 17 --- even numbers --- 12 14 16 Total 6 number processed.