Home

 › 

Articles

 › 

Functional Interface in Java: What You Need To Know

Portrait of african american developer using laptop to write code sitting at desk with multiple screens parsing algorithm in software agency. Coder working on user interface using portable computer.

Functional Interface in Java: What You Need To Know

Key Points

  • A functional interface in Java is an interface with a single abstract method, making it easier to integrate lambda expressions into Java.
  • Lambda expressions are shorthand versions of functions that can be assigned to variables declared as functional interfaces.
  • Some built-in functional interfaces in Java include Predicate, Function, Consumer, and Supplier.
  • Functional interfaces can help create more readable and maintainable code in Java, even though it is not a functional language.

The functional interface in Java is a useful tool that can be used to promote cleaner programming practices and make it easier to build upon existing code bases.

In today’s guide, we will go over what functional interfaces are, the functional interfaces built into Java, and how they can be used to their fullest. Let’s dive right in!

What is a Functional Interface?

Put simply, a functional interface is an interface with a single abstract method. They are usually created for a single purpose, and they make it easier to integrate lambda expressions into Java.

Here’s an example of a functional interface:

@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);
}

The purpose of Calculator is to enable a programmer to make a quick lambda expression that can be used to make a given calculation. 

As can be seen, there is only one method, calculate, and it accepts two arguments for an arbitrary mathematical expression. Note that the @FunctionalInterface annotation is not necessary, but it ensures that you are creating a proper functional interface. If we wanted to actually use the interface, we could do something like this:

Calculator add = (a, b) -> a + b;
System.out.println(add.calculate(2, 3)); // Output: 5

Here, Calculator is used as a data type, and a lambda expression is assigned to it.

functional interface in java example
The above example creates two implementations of the Calculator functional interface: one for addition and one for multiplication. It uses lambda expressions to define the calculate method for each, then calls the calculate method on each with two numbers.

©History-Computer.com

What is a Lambda Expression?

To really understand the functional interface in Java, you need to know what a lambda expression is. A lambda expression is the shorthand version of any function that can be made to quickly perform a specific task. The general form of a lambda expression is:

(parameter1, parameter2, ...) -> {
    // Body of the lambda expression
    // This can be a single statement or a block of code
}

Lambda expressions can be assigned to a variable that is declared as a functional interface, and this allows for their generic functionality.

Types of Built-In Functional Interface in Java

There are many functional interfaces that are built into Java, and you may have used some of them before. Some of them utilize generics, as designated by <T> or <T, R>.

Predicate<T>

Predicates take in an argument of type T and return a boolean value. For example, if we wanted to check if a number is even, we could write:

Predicate<Integer> isEven = n -> n % 2 == 0;
System.out.println(isEven.test(4)); // Output: true
System.out.println(isEven.test(7)); // Output: false

Function<T, R>

As can be assumed by its name, Function is used to represent functions. They take in an argument of type T and return a value of type R. If we wanted to take in a string and return its length, we could write:

Function<String, Integer> stringLength = str -> str.length();
System.out.println(stringLength.apply("Hello")); // Output: 5

Consumer<T>

A Consumer represents an operation performed with a given argument. It takes in an argument of type T and performs some action on it. For example, it can be used to print out every element of a list:

Consumer<String> printElement = str -> System.out.println(str);
List<String> list = Arrays.asList("Apple", "Banana", "Orange");
list.forEach(printElement);

Supplier<T>

A Supplier does not take any arguments, but it produces a value of type T. This can be useful in certain scenarios, such as if we want to generate a random number. Here’s how we can create a Supplier that does this:

Supplier<Double> randomSupplier = () -> Math.random();
System.out.println(randomSupplier.get());

Functional Interface in Java: Wrapping Up

Although they may not always be necessary for your programs, if used correctly, functional interfaces can help you create more readable and maintainable code. 

Java is not a functional language (rather, it is considered an object-oriented language), but this tool is invaluable all the while. There is much more to know about functional interfaces, and we encourage you to learn as much as you can on your programming journey!

Summary Table

Functional InterfaceDescriptionExample
Predicate<T>Takes in an argument of type T and return a boolean value.Check if a number is even
Function<T, R>Used to represent functions. They take in an argument of type T and return a value of type R.Take in a string and return its length
Consumer<T>Represents an operation performed with a given argument. It takes in an argument of type T and performs some action on it.Print out every element of a list
Supplier<T>Does not take any arguments, but it produces a value of type T.Generate a random number

Frequently Asked Questions

What is a Functional Interface in Java?

A functional interface is an interface that contains a single abstract method. It is created so that it can be assigned its own lambda expression for a specific purpose.

What are the Four Types of Functional Interfaces in Java?

The four main types of functional interfaces in Java are Predicates, Functions, Consumers, and Suppliers.

What is the difference between an interface and a functional interface?

The primary difference between an interface and a functional interface in Java lies in the number of abstract methods they contain. A standard interface can contain multiple abstract methods, whereas a functional interface can contain only a single abstract method.

Why can we use functional interfaces in Java?

Functional interfaces in Java are a fundamental part of Lambda expressions, which are a major feature introduced in Java 8. They allow you to write more concise and efficient code by treating functions as method arguments or code as data.

Is a functional interface mandatory in Java?

No, using a functional interface is not mandatory in Java. It is merely a tool that can be used to write cleaner, more efficient code, especially when working with lambda expressions.

To top