Tech Master Tutorials
Email Facebook Google LinkedIn Pinterest Twitter
Home Java Java 8 Java Interview Questions Java Programming

Functional Interfaces

Java 8 has introduced a new concept of Functional interfaces. A functional interface is an interface with only one abstract method.
Functional interfaces can be easily instantiated using Lambda expressions. Functional interfaces can also be instantiated using
anonymous inner classes but using lambda expressions make the code quite compact and easy to understand.

Example :
forEach() method defined in the collection classes take a functional interface Consumer as a parameter.
Definition of forEach method:
default void forEach(Consumer action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
Consumer Interface: This is a functional interface whose functional method is accept(Object).
Interface definition :
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}
So in the following example, instantiating Consumer functional interface and passing it to the forEach method.
package LambdaExpression;

import java.util.HashSet;

public class LambdaTestInterator {
	
	public static void main(String[] args) {
	
		HashSet<Integer> intSet=new HashSet<>();
		
		intSet.add(1);
		intSet.add(2);
		intSet.add(3);

		/*Passing a Lambda Expression for Consumer functional interface defined in java.util.function package. 
		As forEach method defined for collection classes receives the Consumer reference, a lambda expression is
		being passed for the Consumer functional interface interface. The lambda expression is passed for the get()
		method. Represents an operation that accepts a single input argument and returns no result. */

		Consumer consumerInstance=intVal -> System.out.println(intVal);
		
		intSet.forEach(consumerInstance);
	}
}