Functional Interface in Java

Back to home
Logicmojo - Updated Jan 11, 2023



Introduction

A functional interface is defined as an interface with only one abstract method. Only one sort of functionality can be displayed on a functional interface. Beginning with Java 8, we can use lambda expressions to represent the instance of a functional interface.

There can be any number of default and static methods with implementation in a functional interface. Functional interfaces in Java include the Runnable, ActionListener, and Comparable interfaces.

Functional Interfaces are also known as Single Abstract Method Interfaces. They're also known as SAM interfaces. Functional interfaces are a new feature in Java that provides users with a fundamental programming tool.

Java SE 8 introduces functional interfaces, as well as Lambda expressions and Method references, to make code more readable, clean, and straightforward. Interfaces that ensure that just one abstract method is present are known as functional interfaces. The @FunctionalInterface annotation is used to represent functional interfaces and allows them to be used and performed. As previously indicated, functional interfaces can only have one abstract method. They can, however, include any number of default and static methods.

Before Java 8, we had to create anonymous inner class objects or implement these interfaces.

class Test {
	public static void main(String args[])
	{
		// create anonymous inner class object
		new Thread(new Runnable() {
			@Override public void run()
			{
				System.out.println("New thread created");
			}
		}).start();
	}
}


From Java 8, we may use the following syntax to connect lambda expressions to the functional interface object:

class Test {
	public static void main(String args[])
	{

		// lambda expression to create the object
		new Thread(() -> {
			System.out.println("New thread created");
		}).start();
	}
}

@FunctionalInterface Annotation

The @FunctionalInterface annotation can be used to check if a functional interface has only one abstract method.

The compiler displays a 'Unexpected @FunctionalInterface annotation' alert if the functional interface contains more than one abstract method. However, there is no obligation to utilise this annotation.

Implementation in Java

//Program to implement a user-defined functional interface using lambda expressions
@FunctionalInterface
interface Square {
  int calculateSquare(int x);
}
public class Test {
  public static void main(String args[]) {
    int num = 10;
    //lambda expression to define the calculate method
    Square sq = (int x) - >x * x;
    int answer = sq.calculateSquare(num);
    System.out.println("The square of the number is: " + answer);
  }
}

Built-in Functional Interfaces in Java

For common usage situations, Java provides a set of functional interfaces. As a result, there's no need to make your own functional interfaces for each and every use case. In this section, we'll go over some of the built-in Java functional interfaces included in the java.util.function package.

Many built-in functional interfaces are available in Java 8's java.util.function package, such as:

1. Function

The Java Function interface is java.util.function. The function interface is one of Java's most important functional interfaces. The Function interface represents a method that takes only one parameter and returns only one value.

The definition of Function interface looks like:

public interface Function < T,R > {
  public < R > apply(T parameter);
}


2. Predicate

The java.util.function is a class that represents a function in Java. Predicate is a simple function that is represented by a functional interface. This function takes a single parameter and returns true or false depending on whether it is true or false.

The definition of Predicate functional interface looks like:

public interface Predicate {
  boolean test(T t);
}

Implementation in Java

import java.util. * ;
import java.util.function.Predicate;
class Main {
  public static void main(String args[]) {
    List < String > names = Arrays.asList("Logic", "Mojo", "Java", "Tutorials", "TV2");
  
    Predicate < String > p = (s)->s.startsWith("T");
  
    for (String st: names) {
  
      if (p.test(st)) System.out.println(st);
    }
  }
}


3. Supplier

The Java Supplier interface represents a function that returns some kind of value. This interface works in the same way as a factory interface.

Here's an example of how to use the Java Supplier interface:

Supplier < Integer > supplier = () - >new Integer((int)(Math.random() * 1000D));

4. Consumer

The java.util.function package's Consumer interface is a functional interface that represents a function that takes a value but doesn't return anything. Among other things, the Java Consumer interface can be used to print some values, write a value to a file, or transfer a value over the network.

Here's an example of a Java Consumer interface implementation:

Consumer < Integer > consumer = (value) - >System.out.println(value);


With this article at Logicmojo, you must have the complete idea of Functional Interface in Java