Table of contents
1.
Introduction
2.
Functional Interface
2.1.
Example of Functional Interface in Java
2.1.1.
Explanation
2.1.2.
Output
3.
Types of Functional Interfaces in Java
3.1.
1. Consumer
3.2.
2. Predicate
3.3.
3. Function
3.4.
4. Supplier
4.
Built-in Java Functional Interfaces
5.
Frequently Asked Questions
5.1.
What is functional interface in Java?
5.2.
What do you understand by a lambda expression?
5.3.
Is it possible to have more than one abstract method for a functional interface?
5.4.
What are the ways to create a functional interface?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Functional Interface in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello Ninjas, welcome to this article on the topic of functional interface in Java. Have you ever thought about how to implement and why to use a functional interface in Java? If not, and you want to know about it, then don't worry, ninjas. Coding Ninjas got your back. We will clear all your doubts.

functional interface in java

In this article, we will discuss about the functional interface in Java. We will discuss how we can implement it. We will also discuss its types. So, a functional interface only has one abstract method. Before diving into the topic, let us understand what an interface is in Java.

Functional Interface

As we have already mentioned, a functional interface has only one abstract method in Java. It is also known as a SAM(Single Abstract Method) interface in Java. We can use functional interfaces where methods are treated as values, such as lambda expressions. This type of interface provides us with a concise way to represent an anonymous method.

functional interface

In Java 8, we got this type of interface along with an amazing feature called lambda expression. The @FunctionalInterface annotation indicates that an interface is a functional interface. 

Now you might be thinking, how this functional interface looks like. So, let us understand this interface with the help of an example.

Example of Functional Interface in Java

Here is an example of the functional interface in Java:

@FunctionalInterface
interface GreetingForNinjas {
  void greetNinja(String nameOfNinja);
}
You can also try this code with Online Java Compiler
Run Code


This code defines a functional interface called GreetingForNinjas that has a single abstract method called greetNinja(). The method takes only a single parameter of type String and returns no value.

The @FunctionalInterface annotation is an optional annotation for the functional interface. This annotation tells the compiler that this interface is a functional interface. If you try to add one more abstract method it will throw an error because of the functional interface property of having only one abstract method.

Now we can use this functional interface to greet a Ninja. 

public class NinjaGreetings {
  public static void main(String[] args) {
    // Creating a lambda expression
    GreetingForNinjas greetNinja = (nameOfNinja) -> System.out.println("Hello, " + nameOfNinja + "!");
    
    // Using the lambda expression as a value
    greetNinja.greetNinja("Narayan Mishra"); 
  }
}
You can also try this code with Online Java Compiler
Run Code

Explanation

In this example, a lambda expression is used to implement the GreetingForNinja interface. The lambda expression takes a single parameter, nameOfNinja, and uses it to print a greeting message. Then the greetNinja() method of the GreetingForNinja interface is called with the nameOfNinja.

Output

Hello, Narayan Mishra!

Types of Functional Interfaces in Java

There are different types of functional interfaces present in the java.util.function package. Let us understand a few of them:

1. Consumer

A Consumer is a functional interface that represents an operation that accepts an input, performs some action on it, but does not return a result in the Java language's java.util.function package. It accepts an argument and executes the operation. It is often used for side-effect activities like printing, logging, or object modification. Accept is the only abstract method that the Consumer interface defines.  It helps to represent an operation that accepts a single input argument and returns no result.

Example

import java.util.function.Consumer;
public class Example {
   public static void main(String[] args) {
       // Define a Consumer to print a string
       Consumer<String> printString = str -> System.out.println(str);
       
       // Use the Consumer to print a message
       printString.accept("Consumer Functional Interface");
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Consumer Functional Interface

2. Predicate

A Predicate is a functional interface that represents a boolean-valued function of an input in the Java java.util.function package. It is frequently used to put a condition to the test and see if it holds true or not. One abstract method named test is defined in the Predicate interface. It helps to represent a predicate or boolean-valued function of one argument. It is used to filter out the values from the collection in Java. 

Example

import java.util.function.Predicate;
public class Example {
   public static void main(String[] args) {
       // Define a Predicate to check if a number is even
       Predicate<Integer> isEven = num -> num % 2 == 0;
       
       // Test the Predicate
       boolean result = isEven.test(10);
       System.out.println("Is 10 even? \n" + result); // Output: Is 10 even? true
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Is 10 even? 
true

3. Function

A function that takes an input and produces an output is represented by a functional interface called a function in Java's java.util.function package. Data transformation or mapping from one type to another is frequently utilised. The apply abstract method, which accepts an argument and produces a result, is the only one that the Function interface defines.


Example

import java.util.function.Function;
public class Example {
   public static void main(String[] args) {
       // Define a Function to double a number
       Function<Integer, Integer> doubleNumber = num -> num * 2;
       
       // Use the Function to double a number
       int result = doubleNumber.apply(10);
       System.out.println("Double of 10 is: " + result);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Double of 10 is: 20

4. Supplier

A Supplier is a functional interface that represents a supplier of results in Java's java.util.function package; when called, it does not require any input and instead returns a result. It is frequently utilised when you need to create or compute values inefficiently.

 

Example

import java.util.function.Supplier;
public class Example {
   public static void main(String[] args) {
       // Define a Supplier to generate a random number
       Supplier<Double> randomNumberSupplier = () -> Math.random();
       
       // Use the Supplier to generate a random number
       double randomVal = randomNumberSupplier.get();
       System.out.println("Random Number: " + randomVal);
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Random Number: 0.8635943284489002

Built-in Java Functional Interfaces

There are four built-in functional interfaces in Java:

  1. Runnable: The runnable interface in Java helps us to define a method called run(). This method doesn't takes any arguments and returns no value. It is used to represent a task that can be executed asynchronously.
     
  2. Callable: The callable interface in Java helps us to define a method called call(). This method returns a value of a specific type and can throw an exception. It is used to represent a task that can be executed asynchronously and that returns a result.
     
  3. Comparable: The comparable interface in Java helps us to define a method called compareTo(). This method takes an object of the same type as the implementing class. It returns an integer value indicating the ordering of the two objects. It is used to represent objects that have a natural ordering, such as numbers or strings.
     
  4. ActionListener: The ActionListener interface in Java helps us to define an abstract method actionPerformed(ActionEvent e). This interface handles events triggered by actions such as button clicks, menu selections, and other user interactions.

Frequently Asked Questions

What is functional interface in Java?

A functional interface is a type of interface. It has only one abstract method. This interface is used to show a single functionality. We can use functional interfaces where methods are treated as values, such as lambda expressions. 

What do you understand by a lambda expression?

A lambda expression is a feature of Java 8. It is the easiest way to declare a function along with its parameters. It is a short way in Java to express a function. This can work as a value, and later on, we can use this value in our code.

Is it possible to have more than one abstract method for a functional interface?

No, this is not possible in the case of a functional interface in Java. This interface can only have one abstract method. If it has more than one abstract method, then this will not be anymore a functional interface.

What are the ways to create a functional interface?

There are several ways to create a functional interface. We can create a functional interface by defining an interface with only one abstract method. We can also use the @FunctionalInterface annotation. This annotation helps us to indicate an interface as a functional interface.

Conclusion

In this article, we have discussed the functional interface in Java. We have also discussed examples by using this interface. With the advent of lambda expressions in Java 8, functional interfaces have become increasingly important in Java development. They give programmers an easy method to treat functions as first-class citizens, allowing them to create clearer and more expressive code.

 You can check out our other blogs to enhance your knowledge:

Happy Learning!!

Live masterclass