Thursday, August 16, 2018

Java8 - Consumer interface tutorials| Functional Interface examples in java

Java8 Consumer interface

Consumer interfaces are functional interfaces in java.util.function page and introduced in Java 8. It takes a single parameter and outputs any result.
Functional interfaces has a single abstract method.This one abstract method accept() and default method is andThen()
This is defiend in java.util.function package since java 8 version.
This can be assigned 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 flow of programming
@FunctionalInterface
public interface Consumer { void accept(T t);
}

Simple Consumer accept the 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");
 }
}
Hi Frank

Consumer addThen 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 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 is
SAMPLEDATA
SAMPLEDATA
OTHERS

Related article


EmoticonEmoticon