Java8 - Consumer interface tutorials| Functional Interface examples in java
What are Consumer interfaces in Java8?
Consumer
interfaces are functional interfaces in java.util.function
package in Java 8.
It takes a single parameter and outputs any result.
Functional interfaces contains one abstract method accept()
and default method is andThen()
.
This is defined in java.util.function
package since java 8 version.
This can be assigned a target for lambda expressions
as well as method references
.
Consumer interfaces are used to consume the data supplied by streams, process it, and print the result or chain to another interface in a Stream programming flow.
@FunctionalInterface
public interface Consumer { void accept(T t);
}
Simple Consumer accept abstract method example
accept
method takes input and outputs nothing, but it prints the result to the console
import java.util.function.Consumer;
public class MyConsumerExample {
static void displayName(String name) {
System.out.println("Hi " + name);
}
public static void main(String[] args) {
Consumer<String> consumerString = MyConsumerExample::displayName;
consumerString.accept("Frank");
}
}
Output:
Hi Frank
java8 Consumer addThen default method example
addThen()
is a default method of Consumer interface. This outputs new consumer by aggregation result of the consumer that applied to another instance of another consumer.
This is an example of consumer lambda parameters addThen() has the following syntax
default Consumer<T> andThen(Consumer<? super T> after)
Example:
import java.util.function.Consumer;
public class MyConsumerExample {
static void displayName(String name) {
System.out.println("Hi " + name);
}
public static void main(String[] args) {
Consumer<String> c = (value) -> System.out.println(value.toUpperCase());
c.andThen(c).accept("sampledata");
c.accept("others");
}
}
output:
SAMPLEDATA
SAMPLEDATA
OTHERS
Conclusion
In this tutorial, Learned Consumer interface and its usage with examples of the abstract method and default method and also examples using lambda expression and method references.