×

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

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java. Creating String objects We create String objects...

5 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 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.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.