Java 8 Functional Interface

kapil sharma
2 min readMar 20, 2018

--

Functional Interface

  • Any interface which has only one abstract method is a functional interface
  • This interface can be used anywhere a functional interface is eligible to use
  • @FunctionalInterface annotation explicitly tells the compiler to treat the interface as Functional interface. Compiler will make sure that all the rules are followed to make interface as Functional.

Usage: Implementation of functional interface’s abstract method can be passed around as lambada expression.

Example of pre-existing Functional Interfaces in Java

Some of the commonly used functional interface in java 8

  • Function and BiFunction
  • Predicate and BiPredicate
  • Consumer and BiConsumer
  • Supplier

Consumer<T>

  • Consumer<T> is an in-built functional interface.
  • It can be used in all the places where an object has to be consumed i.e taken as input and perform some operation on the object without returning any result.
  • Since Consumer is a functional interface, hence it can be used as the assignment target for a lambda expression or a method reference.
  • It contains two methods accept & andThen.

Example to use Consumer

BiConsumer: It is same as Consumer but it takes two input argument instead of one. Rest all the things are same.

Supplier<T>

  • Supplier<T> is an in-built functional interface.
  • In reverse to the Consumer, Supplier can be used at places where you don’t take any input for an operation but return an Object

Usage Example

Predicate<T>

  • Predicate<T> is an in-built functional interface.
  • It can be used at places where you want to perform a test on given input object
  • There are few other default method provided in predicate which can help in performing other operation like and(), or(), negate()
  • BiPredicate takes two arguments and does the same work

Usage Example

I have taken reference from https://www.javabrahman.com and few other websites.

--

--

No responses yet