×

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity.

Functions in the Java programming language are part of a class, and if someone wants to use them, they have to use the class or object of the class to call any function.

Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short, they are also known as SAM (Single Abstract Method) interfaces. Functional interfaces in Java are the new feature that provides users the approach of fundamental programming.

Functional interfaces are included in Java SE 8 with Lambda expressions and Method references in order to make code more readable, clean, and straightforward. It ensures that they include precisely only one abstract method. It is used and executed by representing the interface with an annotation called @FunctionalInterface. As described earlier, functional interfaces can contain only one abstract method. However, they can include any quantity of default and static methods. 

In Functional interfaces, there is no need to use the abstract keyword as it is optional to use the abstract keyword because, by default, the method defined inside the interface is abstract only. We can also call Lambda expressions as the instance of functional interface.

Example of Functional Interfaces in Java

public interface MyFunctionalInterface1 {


    public void execute();


}

The above is an example of a functional interface in Java because it only contains only a single method, and there is no implementation inside that method. Usually, in a Java functional interface, there are no implementations of the method or process which is declared inside it. However, it can contain the implementations of the default methods and static methods which are displayed inside it. 

Following is another instance of the functional interface in Java, with implementations of some of the methods, i.e., static and default methods:

public interface MyFunctionalInterface2{


    public void execute();


    public default void print(String msg) {
        System.out.println(msg);
    }


    public static void print(String msg, PrintWriter writer) throws IOException {
        writer.write(msg);
    }


}

In the above example, the interface MyFunctionalInterface2 is still counted as a functional interface because it comprises mainly a single abstract method (non-implemented method).

Some Built-in Java Functional Interfaces

Since Java SE 1.8 onwards, there are many interfaces which are converted into the functional interface. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows:

  • Runnable: It contains only the run() method.
  • Comparable: It contains only the compareTo() method.
  • ActionListener: It contains only the actionPerformed() method.
  • Callable: It contains only the call() method.

Java SE 8 included four types of functional interfaces in Java that can be applied in multiple situations. These are:

  1. Consumer
  2. Predicate
  3. Function 
  4. Supplier

Amidst the previous four interfaces, the first three interfaces, i.e., Consumer, Predicate, and Function, likewise have additions that are provided beneath:

  1. Consumer: Bi-Consumer
  2. Predicate: Bi-Predicate
  3. Function: Bi-Function, Unary Operator, Binary Operator 

Consumer:

The consumer interface of the functional interface is the one that accepts only one argument or a gentrified argument. The consumer interface has no return value. It returns nothing. There are also functional variants of the Consumer — DoubleConsumer, IntConsumer, and LongConsumer. These variants accept primitive values as arguments. 

Other than these variants, there is also one more variant of the Consumer interface known as Bi-Consumer. 

Bi-Consumer:

Bi-Consumer is the most exciting variant of the Consumer interface. The consumer interface takes only one argument, but on the other side, the Bi-Consumer interface takes two arguments. Both, Consumer and Bi-Consumer has no return value. It also returns noting just like the Consumer interface. It is used in iterating through the entries of the map. 

Syntax / Prototype of Consumer Functional Interface:

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

The above implementation of the Java Consumer functional interface prints the value passed as a parameter to the print statement. This implementation uses the Lambda function of Java.

Predicate:

In scientific logic, a function that accepts an argument and, in return, generates a boolean value as an answer is known as a predicate.

Similarly, in the Java programming language, a predicate functional interface of Java is a type of function which accepts a single value or argument and does some sort of processing on it, and returns a boolean (True/ False) answer. The implementation of the Predicate functional interface also encapsulates the logic of filtering (a process that is used to filter stream components on the base of a provided predicate) in Java.

Just like the Consumer functional interface, Predicate functional interface also has some extensions. These are IntPredicate, DoublePredicate, and LongPredicate. These types of predicate functional interfaces accept only primitive data types or values as arguments.  

Bi-Predicate:

Bi-Predicate is also an extension of the Predicate functional interface, which, instead of one, takes two arguments, does some processing, and returns the boolean value.

Syntax of Predicate Functional Interface:

public interface Predicate<T> {


    boolean test(T t);


}

The predicate functional interface can also be implemented using a class. The syntax for the implementation of predicate functional interface using a class is given below - 

public class CheckForNull implements Predicate {


    @Override
    public boolean test(Object o) {


        return o != null;


    }
}

The Java predicate functional interface can also be implemented using Lambda expressions. The example of implementation of Predicate functional interface is given below - 

Predicate predicate = (value) -> value != null;

The above implementation of functional interfaces uses Lambda expressions that is manageable and effective than the one implemented by using a class. As both the implementations are doing the same work, i.e., returning the same output.

Function:

 A function is a type of functional interface in Java that receives only a single argument and returns a value after the required processing. There are many versions of Function interfaces because a primitive type can’t imply a general type argument, so we need these versions of function interfaces. Many different versions of the function interfaces are instrumental and are commonly used in primitive types like double, int, long. The different sequences of these primitive types are also used in argument.

These versions are:

Bi-Function:

The Bi-Function is substantially related to a Function. Besides, it takes two arguments, whereas Function accepts one argument. 

The prototype and syntax of Bi-Function is given below:

@FunctionalInterface
public interface BiFunction<T, U, R> 
{


   R apply(T t, U u);
    ……...


}

In the above code of interface, T, U are the inputs, and there is only one output that is R. 

Unary Operator and Binary Operator:

There are also two other function interfaces which are named as Unary Operator and Binary Operator. They both extend the Function and Bi-Function, respectively. In simple words, Unary Operator extends Function and Binary Operator extends Bi-Function. 

The prototype of the Unary Operator and Binary Operator is given below:

1. Unary Operator:

@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, U> 
{
    ……...
}

2. Binary Operator:

@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, U, R> 
{
    ……...
}

We can understand front the above example that the Unary Operator accepts only one argument and returns a single argument only. Still, in Unary Operator both the input and output values must be identical and of same type. 

On the other way, Binary Operator takes two values and return one value comparable to Bi- Function but similarly like Unary Operator, the input and output value type must be identical and of same type.

Supplier:

The Supplier functional interface is also a type of functional interface that does not take any input or argument and yet returns a single output. The kind of functional interface is generally used in the lazy generation of values. Supplier functional interfaces are also used for defining the logic for the generation of any sequence.

For example, the logic behind the Fibonacci Series can be generated with the help of the Stream.generate method that is implemented by the Supplier functional Interface. 

The different extensions of the Supplier functional interface hold many other supplier functions like BooleanSupplier, DoubleSupplier, LongSupplier, and IntSupplier. The return type of all these further specializations is their corresponding primitives only. 

Syntax / Prototype of Supplier Functional Interface is:

@FunctionalInterface
public interface Supplier<T>{


// gets a result
………….


// returns the specific result
…………


T.get();


}

The java.util.function package includes many different functional interfaces that are managed by JDK and can be used by and available for end-users. The interfaces described in this package are also annotated with @FunctionalInterface annotation.

There are many other functional interfaces in Java other than the one which are described above. These functional interfaces are also part of the java.util.function package. These are:

  • BooleanSupplier: It signifies a type of supplier functional interface that returns boolean-valued results.
  • DoubleBinaryOperator: It depicts an operation on two operands of type double and returns a value of double type. 
  • DoubleConsumer: It signifies an operation that accepts a single argument of type double and no result is returned.
  • DoubleFunction<R>: It portrays a function that takes a value of type double and returns a specified result.
  • DoublePredicate: It describes a boolean-valued function (which is also known as the predicate) of an argument of type double. 
  • DoubleSupplier: It signifies a type of supplier functional interface of double type.
  • DoubleToIntFunction: It denotes a function that receives an argument of type double and gives a result of type int. 
  • DoubleToLongFunction: It denotes a function that receives an argument of type double and gives a result of type long. 
  • DoubleUnaryOperator: It describes an operation on a single operand of type double and gives a result of type double.
  • IntBinaryOperator: It signifies an operation on two operands of type int and produces a result of type int.
  • IntConsumer: It signifies an operation that accepts a single argument of type int and no result is returned.
  • IntFunction<R>: It portrays a function that accepts an argument of type int and returns a specified result.
  • IntPredicate: It describes a boolean-valued function (which is also known as the predicate) of an argument of type int.
  • IntSupplier: It signifies a type of supplier functional interface of int type.
  • IntToDoubleFunction: It denotes a function that receives an argument of type int and gives a result of type double.
  • IntToLongFunction: It denotes a function that receives an argument of type int and gives a result of type long.
  • IntUnaryOperator: It denotes a process on only one operand of the type int and result returned is also of type int.
  • LongBinaryOperator: It represents a process on two operands of type long and which returns a long type result.
  • LongConsumer: It signifies a process that accepts only one value of type long and here no result is returned.
  • LongFunction<R>: It portrays a function that accepts an argument of type long and returns a specified result.
  • LongPredicate: It describes a boolean-valued function (which is also known as the predicate) of an argument of type long.
  • LongSupplier: It signifies a type of supplier functional interface of long type.
  • LongToDoubleFunction: It denotes a function that receives an argument of type long and gives a result of type double.
  • LongToIntFunction: It denotes a function that receives an argument of type long and gives a result of type int.
  • LongUnaryOperator: It denotes a process on only one operand of the type long and result returned is also of type long.
  • ObjDoubleConsumer<T>: It describes an operation that takes an argument of type double and an object and returns no result.
  • ObjIntConsumer<T>: It describes an operation that takes an argument of type int and an object and returns no result.
  • ObjLongConsumer<T>: It describes an operation that takes an argument of type long and an object and returns no result.
  • ToDoubleBiFunction<T, U>: It signifies a function that receives two values and the result returned is of type double.
  • ToDoubleFunction<T>: It describes a function that provides a result of type double. 
  • ToIntBiFunction<T,U>: It signifies a function that receives two values and the result returned is of type int.
  • ToIntFunction<T>: It describes a function that provides a result of type int.
  • ToLongBiFunction<T,U>:  It signifies a function that receives two values and the result returned is of type long.
  • ToLongFunction<T>: It describes a function that provides a result of type long.

These are the different functional interfaces in Java other than the usual ones. 

Examples of Functional Interfaces in Java 

Now it’s time to see different examples of Java functional interfaces and also their expression and their uses in the Java programming language.

Example 1 - In example 1, let us see the use of java.util.function.function and its built-in functional interface.

FunctionalInterfaceExample1.java

import java.util.function.*;
  
    public static void main (String args[]){
        
        FunctionalInterfaceExample1 obj = new FunctionalInterfaceExample1();
        
        Integer sq= obj.apply(10);
        
        System.out.println("Square of 10 is " + sq);
    }


public class FunctionalInterfaceExample1 implements Function<Integer, Integer>{
    
    @Override
    public Integer apply (Integer x){
    
        return x*x;
    
    }
}

Output: 

Square of 10 is 100

In the above code, we are implementing the following interface in the class. It is present in the java.util.function package.

Interface: 

package java.util.function;


public interface Function<T,R>{


public <R> apply(T inputparams);


}

Example 2 - In the example 2, let us see how functional interfaces in Java are designed using lambda expressions.

FunctionalInterfaceExample2.java

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


Runnable r = () -> {System.out.println ("Thread running.....");};


// above creating an instance of functional interface


new Thread(r).start(); 


}
}

Output:

Thread running.....

In the above code, we have applied and used the Java Lambda expressions in order to implement the functional interfaces in Java.

Example 3 - In this example 3, let us see the performance of another built-in functional interface known as Consumer interface in Java to traverse through a List.

FunctionalInterfaceExample3.java

import java.util.function.*;
import java.util.*;
 
public class FunctionalInterfaceExample3{
    
    public static void main (String args[]){
        
        ArrayList<Integer> arr = new ArrayList<Integer>();
        
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        arr.add(5);
        arr.add(6);
        
        // Iterate arraylist using consumer
        arr.forEach(new Consumer<Integer>(){
            
            @Override
            public void accept(Integer item){
                
                System.out.println(item);
                
            }
        });
    }
}

Output - 

1
2
3
4
5
6

Example 4 - In this example, let us see the performance of another built-in Predicate functional interface in Java to iterate a List using Lambda Expressions.

FunctionalInterfaceExample4.java

import java.util.*;
import java.util.function.Predicate;
  
public class FunctionalInterfaceExample4
{
    public static void main(String args[])
    {
  
        ArrayList<String> people = Arrays.asList("Ram","Shyam","Ramesh","Suresh","Anupam");
  
      // using Java Lambda expressions to create an object of type Predicate<String>
        Predicate<String> p = (n)->n.endsWith("m");
  
        // Iterating through all the members of list
        for (String str:people)
        {
            // calling the method test
            if (p.test(str))
                System.out.println(str);
        }
    }
}

Output:

Ram
Shyam
Anupam

Points to Remember

Here are some significant points regarding Functional interfaces in Java:

  • In functional interfaces, there is only one abstract method supported. If the annotation of functional interface, i.e., @FunctionalInterface is not implemented or written with a function interface, more than one abstract method can be declared inside it. However, in this situation with more than one functional interface, that interface will not be called a functional interface. It is called a non-functional interface.
  • There is no as such need of the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking compiler level. Besides this, it is optional.
  • An infinite number of methods (whether static or default) can be added in the functional interface. In simple words there is no limit of a functional interface containing static and default methods.
  • Overriding methods from the parent class do not violate the rules of a functional interface in Java.

Conclusion 

The above content or article provides a precise knowledge and processing of the Java functional interfaces. The significant benefit of using functional interfaces of the Java SE 8 is that it allows for support for lambda expressions. It support helps in eliminating a lot of redundant code. Java functional interfaces and lambda expressions together helps in writing of small, efficient, and cleaner code.

Functional interfaces in Java also helps in making the code more precise and straight forward.


Related Topics

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.