- A functional interface allows only 1 abstract method
- More than 1 default methods
- More than 1 static methods
- Let us override java.lang.Object ckass methods
- Concrete method
- To enable functional programming in java.
- To enable lambda expression
- To use method referencing
In functional programming we can send another function as method parameter.
By using @FunctionalInterface annotation
- By writing separate Implementation class
- By annonymous inner class
- By lambda expression
- By Method references
- Operator
::
- Signature must be same (name is not mandatory)
- Implementation of method must be static
- A Consumer is a functional interface that accepts a single input and returns no output.
- Consumer interface has two methods:
void accept(T t);
default Consumer<T> andThen(Consumer<? super T> after);
- The
accept
method is the Single Abstract Method (SAM) which accepts a single argument of type T. andThen
is a default method used for composition or chaining.andThen
takes a consumer as input and returns a consumer.
public static void printUsingAcceptMethod(){
// Create a function that prints what ever is passed through accept method of consumer interface.
Consumer<String> printConsumer = t -> System.out.println(t);
Stream<String> cities = Stream.of("Sydney", "Dhaka", "New York", "London");
// foreach method of stream interface takes a consumer through parameter.
cities.forEach(printConsumer);
}
public void printUsingAndTherMethod(){
List<String> cities = Arrays.asList("Sydney", "Dhaka", "New York", "London");
// This consumer converts an string list into upper case.
Consumer<List<String>> upperCaseConsumer = list -> {
for(int i=0; i< list.size(); i++){
list.set(i, list.get(i).toUpperCase());
}
};
// This Consumer print list of string
Consumer<List<String>> printConsumer = list -> list.stream().forEach(System.out::println);
// Chaining consumers using andThen
upperCaseConsumer.andThen(printConsumer).accept(cities);
}