In this tutorial, we will learn how to use the Consumer functional interface with an example.
Learn and master in Java 8 features at Java 8 Tutorial with Examples
Video Tutorial
Overview
java.util.function.Consumer is a functional interface whose functional method (single abstract method) is accept(T t). The Consumer interface represents an operation that takes single argument T and returns no result:
@FunctionalInterface
public interface Consumer < T > {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
Consumer Interface Example #1
The following example shows how to use the accept() method of the Consumer interface with a lambda expression.
package com.javaguides.java.functionalinterfaces;
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
// example 1
Consumer < String > consumer = (t) -> System.out.println(t);
consumer.accept("Ramesh");
}
}
Output:
Ramesh
Consumer Interface Example #2
The following example shows how to use the default method andThen() of the Consumer interface with a lambda expression:
package com.javaguides.java.functionalinterfaces;
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
// example 2
Consumer < String > consumer2 = (input) -> System.out.println(input + " World !");
Consumer < String > consumer3 = (input) -> System.out.println(input + " Java");
consumer2.andThen(consumer3).accept("hello");
}
}
Output:
hello World !
hello Java
Consumer Interface Example #3
The java.lang.Iterable.forEach() method internally uses Consumer interface. Here is the forEach() method implementation:
default void forEach(Consumer << ? super T > action) {
Objects.requireNonNull(action);
for (T t: this) {
action.accept(t);
}
}
In this below example, we create a list of integers and use forEach() method to loop over list and print elements to console:
package com.javaguides.java.functionalinterfaces;
import java.util.Arrays;
import java.util.List;
public class ConsumerDemo {
public static void main(String[] args) {
List < Integer > integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
integers.forEach((t) -> System.out.println(t));
}
}
Output:
1
2
3
4
5
6
7
8
Learn and master in Java 8 features at Java 8 Tutorial with Examples
Comments
Post a Comment
Leave Comment