×

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 try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Java Integer shortValue() method

The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number  Return Value This...

1 minute read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.