Learnitweb

Consumer interface in Java

Consumer interface is predefined functional interface available in Java 8. This interface is available in java.util.function package. This interface represents an operation which accepts an input argument and does not return a result.

Consumer interface has one functional method void accept(T t). There is another default method in Consumer interface:

default Consumer andThen(Consumer after)

void accept(T t)Performs this operation on the provided argument t .
default Consumer andThen(Consumer after)Returns a composed Consumer that performs, this operation followed by the after operation.

A consumer is expected to operate via side-effect.

If error occurs during execution of this operation then after operation will not be executed. If either of the operation throws an error then the error is passed on to the caller of the operation.

Where Consumer is used

Consumer can be used in cases where some operation needs to be performed on a given input without returning a result. For example, when we want to print a given object, consumer is the right functional interface to use.

Consumer functional interface example

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

public class ConsumerExample {
	public static void main(String[] args) {
		//Consumer example to print string
		Consumer<String> consumer = str -> System.out.println(str);
		consumer.accept("hello world");
		
		
		//Consumer example to multiply each element by 2
		
		//Create an list
		List<Integer> list = new ArrayList();
		
		//add elements to list
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(3);
		
		/*Define a consumer. For every element in list multiply
		element by 2*/
		Consumer<List<Integer>> multiply = integerList -> {
			for(int i=0; i< integerList.size(); i++) {
				integerList.set(i, 2* integerList.get(i));
			}
		};
		
		multiply.accept(list);
		
		System.out.println("list after multiplication by 2 :" + list);
	}
}

Output

hello world
list after multiplication by 2 :[2, 4, 6, 6]

Consumer chaining example

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

public class ConsumerChainingExample {
	public static void main(String[] args) {
		//Create list
		List<Integer> l = new ArrayList();
		
		//add elements to list
		l.add(5);
		l.add(6);
		l.add(7);
		
		//Consumer1 multiplies every element of list by 2
		Consumer<List<Integer>> consumer1 = numberList -> {
			for(int i=0; i< numberList.size(); i++) {
				numberList.set(i, 2* numberList.get(i));
			}
		};
		
		//consumer2 prints list
		Consumer<List<Integer>> consumer2 = list -> {
			System.out.println(list);
		};
		
		consumer1.andThen(consumer2).accept(l);
		
	}
}

Output

[10, 12, 14]

In this example we have done the following:

  • Created a list
  • Defined consumer1 which multiplies every element of list by 2
  • Defined consumer2 which prints the list

Example to demonstrate exception in consumer operation

In this example, we have added code 1/0 in consumer1 to generate java.lang.ArithmeticException. Since exception is thrown in consumer1, consumer2 is not executed. The exception is relayed to the caller. In this case main method and then to JVM.

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

public class ConsumerChainingExample {
	public static void main(String[] args) {
		//Create list
		List<Integer> l = new ArrayList();
		
		//add elements to list
		l.add(5);
		l.add(6);
		l.add(7);
		
		//Consumer1 multiplies every element of list by 2
		Consumer<List<Integer>> consumer1 = numberList -> {
			for(int i=0; i< numberList.size(); i++) {
				//code for exception
				System.out.println(1/0);
				numberList.set(i, 2* numberList.get(i));
			}
		};
		
		//consumer2 prints list
		Consumer<List<Integer>> consumer2 = list -> {
			System.out.println(list);
		};
		
		consumer1.andThen(consumer2).accept(l);
		
	}
}

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at ConsumerChainingExample.lambda$0(ConsumerChainingExample.java:19)
	at java.util.function.Consumer.lambda$andThen$0(Consumer.java:65)
	at ConsumerChainingExample.main(ConsumerChainingExample.java:29)