Functional Interface in Java 8 with examples

In Java 8, a Functional interface is an interface that has only one abstract method. This type of interface is also known as a "SAM" (Single Abstract Method) interface.

Functional interfaces are a key feature of the new lambda expressions syntax in Java 8. Lambdas allow you to create a new instance of a functional interface in a very concise and expressive way, which is useful for writing more readable and maintainable code.

Table of Content :

Java 8 provides a number of built-in functional interfaces in the java.util.function package, such as Predicate, Function, Consumer, and Supplier. These interfaces provide a way to perform common functional programming tasks, such as filtering collections, transforming data, and generating values.

Rules for Functional Interface

In Java 8, a functional interface is an interface that has only one abstract method. Here are some rules and guidelines for creating and using functional interfaces in Java:

  • A functional interface must have only one abstract method . This method is known as the functional method or SAM (Single Abstract Method) method.
  • The @FunctionalInterface annotation can be used to indicate that an interface is intended to be a functional interface. This annotation is optional but can help prevent accidental addition of extra abstract methods to the interface.
  • A functional interface can have default methods and static methods , but they must not override the functional method.
  • A functional interface can extend another interface , as long as it does not add any abstract methods that would conflict with the functional method.
  • A lambda expression can be used to create an instance of a functional interface. The lambda expression provides an implementation of the functional method.
  • A method reference can also be used to create an instance of a functional interface. A method reference is a shorthand notation for calling a method that can be used to provide an implementation of the functional method.
  • Functional interfaces can be used with the new stream API and the parallel streams feature introduced in Java 8. Stream operations such as map, filter, and reduce take functional interfaces as parameters.
  • Functional interfaces are a key feature of Java 8 that enable more concise and expressive code, particularly when working with collections and streams . By following these rules and guidelines, you can create and use functional interfaces effectively in your Java code.

Here is an example of a functional interface in Java 8:

@FunctionalInterface public interface AddInterface { int doAddition(int a, int b); }

This interface has only one abstract method, doAddition, which takes two integer parameters and returns an integer. The @FunctionalInterface annotation is optional but can be used to ensure that the interface has only one abstract method and will be used as a functional interface

AddInterface add = (a, b) -> a + b; int result = add.doAddition(21, 20); //41

Functional interface rules with Inheritance

Child inherits methods but no more abstract method is declared.

package com.javacodestuffs.core.java.functional.iface; @FunctionalInterface interface Parent { public int parentMethod(); } // This cannot be FunctionalInterface //@FunctionalInterface interface Child extends Parent { public int childMethod(); // It will also extend the abstract method of the Parent Interface // Hence it will have more than one abstract method // And will give a compiler error Parent child = ()->1; }

Functional Interface with Lambda Expression Examples

Use of Functional Interface with Lambda Expression to find square of any Integer

package com.javacodestuffs.core.java.functional.iface; interface MathInterface { public int squareIt(int num); } public class FunctionalInterfaceWithLambdaExpression { // main method public static void main(String[] args) { // Lambda Expression MathInterface square = (num) -> num * num; // invoke Lambda Expression -> Functional Interface System.out.println(square.squareIt(5)); } }

Output:

25

Predefined functional interfaces

In Java 8, the java.util.function package provides several predefined functional interfaces that can be used for common functional programming tasks. Following are some examples:

Pre-defined Functional Interface (1 argument) - 4

Pre-defined Functional Interface (2 arguments):

  • BiPredicate
  • BiFunction
  • BiConsumer

Primitive Predicate Functional Interface - 3

  • IntPredicate
  • LongPredicate
  • DoublePredicate

Primitive Function Functional Interfaces - 12

  • IntFunction
  • LongFunction
  • DoubleFunction
  • ToIntFunction
  • ToLongFunction
  • ToDoubleFunction
  • IntToLongFunction
  • IntToDoubleFunction
  • LongToIntFunction
  • LongToDoubleFunction
  • DoubleToIntFunction
  • DoubleToLongFunction

Primitive BiFunction Functional Interfaces - 3

  • ToIntBiFunction
  • ToLongBiFunction
  • ToDoubleBiFunction

Primitive Consumer Functional Interfaces- 6

  • IntConsumer
  • LongConsumer
  • DoubleConsumer
  • ObjIntConsumer
  • ObjLongConsumer
  • ObjDoubleConsumer

Primitive Supplier Functional Interfaces - 4

  • IntSupplier
  • LongSupplier
  • DoubleSupplier
  • BooleanSupplier

UnaryOperator Functional Interface and its primitive types - 4

  • IntUnaryOperator
  • LongUnaryOperator
  • DoubleUnaryOperator

BinaryOperator Functional Interface and its primitive types - 3

  • IntBinaryOperator
  • LongBinaryOperator
  • DoubleBinaryOperator

Advantages to use functional interfaces

There are several advantages to using functional interfaces in Java:

  • Concise and expressive code: Functional interfaces allow you to write more concise and expressive code, particularly when combined with lambda expressions. This can make your code more readable and easier to maintain.
  • Type safety: Functional interfaces provide type safety, which means that the compiler can detect errors at compile time rather than at runtime. This can help you catch errors earlier and avoid potential bugs.
  • Composability: Functional interfaces can be composed and combined to create more complex functions. This allows you to build up functionality from simpler pieces, which can make your code more modular and reusable.
  • Performance: Functional interfaces can improve performance by reducing the need for intermediate data structures and loop constructs. This is particularly true when working with large data sets or when performing complex transformations.
  • Compatibility with streams: Functional interfaces are designed to work with the new stream API introduced in Java 8. This allows you to perform complex operations on collections and streams using functional programming techniques.

Overall, functional interfaces provide a powerful and flexible way to express functional programming patterns in Java. By using functional interfaces, you can write more concise, readable, and maintainable code that is less prone to errors and more performant.

Conclusion

In this article we have seen What is Functional Interface in Java 8 with examples along with its benefits to Java language and its developers.