The Wayback Machine - https://web.archive.org/web/20240829190640/https://www.geeksforgeeks.org/functional-interfaces-java/
Open In App

Functional Interfaces in Java

Last Updated : 22 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. There are no solely functions present in a programming language called Java. 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.

Java Functional Interfaces

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, and Comparable are some of the examples of functional interfaces. 

Functional Interface is additionally recognized as Single Abstract Method Interfaces. In short, they are also known as SAM interfaces. Functional interfaces in Java are the new feature that provides users with 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. Functional interfaces are interfaces that ensure that they include precisely only one abstract method. Functional interfaces are 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.

Java Functional Interfaces Example

Example 1:

Before Java 8, we had to create anonymous inner class objects or implement these interfaces.

Java




// Java program to demonstrate functional interface
 
class Test {
    public static void main(String args[])
    {
        // create anonymous inner class object
        new Thread(new Runnable() {
            @Override public void run()
            {
                System.out.println("New thread created");
            }
        }).start();
    }
}


Output

New thread created

Example 2:

Java 8 onwards, we can assign lambda expression to its functional interface object like this: 

Java




// Java program to demonstrate Implementation of
// functional interface using lambda expressions
 
class Test {
    public static void main(String args[])
    {
 
        // lambda expression to create the object
        new Thread(() -> {
            System.out.println("New thread created");
        }).start();
    }
}


Output

New thread created

@FunctionalInterface Annotation

@FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method. In case more than one abstract methods are present, the compiler flags an ‘Unexpected @FunctionalInterface annotation’ message. However, it is not mandatory to use this annotation.

Below is the implementation of the above topic:

Java




// Java program to demonstrate lambda expressions to
// implement a user defined functional interface.
 
@FunctionalInterface
 
interface Square {
    int calculate(int x);
}
 
class Test {
    public static void main(String args[])
    {
        int a = 5;
 
        // lambda expression to define the calculate method
        Square s = (int x) -> x * x;
 
        // parameter passed and return type must be
        // same as defined in the prototype
        int ans = s.calculate(a);
        System.out.println(ans);
    }
}


Output

25

Some Built-in Java Functional Interfaces

Since Java SE 1.8 onwards, there are many interfaces that are converted into functional interfaces. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows – 

  • Runnable –> This interface only contains the run() method.
  • Comparable –> This interface only contains the compareTo() method.
  • ActionListener –> This interface only contains the actionPerformed() method.
  • Callable –> This interface only contains the call() method.

Java SE 8 included four main kinds of functional interfaces which can be applied in multiple situations as mentioned below:

  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 

1. 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 have no return value. It also returns nothing 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);

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

2. 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 that 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. An example of the implementation of the Predicate functional interface is given below – 

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

This implementation of functional interfaces in Java using Java Lambda expressions is more manageable and effective than the one implemented using a class as both the implementations are doing the same work, i.e., returning the same output.

3. 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 the 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 and U are the inputs, and there is only one output which is R. 

Unary Operator and Binary Operator

There are also two other functional interfaces which are named 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 mentioned below :

i. Unary Operator

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

 ii. 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 the same type. 

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

4. 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. This type 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, which is implemented by the Supplier functional Interface. 

The different extensions of the Supplier functional interface hold many other suppliers 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();
 
}

Below is the implementation of the above topic:

Java




// A simple program to demonstrate the use
// of predicate interface
import java.util.*;
import java.util.function.Predicate;
 
class Test {
    public static void main(String args[])
    {
        // create a list of strings
        List<String> names = Arrays.asList(
            "Geek", "GeeksQuiz", "g1", "QA", "Geek2");
 
        // declare the predicate type as string and use
        // lambda expression to create object
        Predicate<String> p = (s) -> s.startsWith("G");
 
        // Iterate through the list
        for (String st : names) {
            // call the test method
            if (p.test(st))
                System.out.println(st);
        }
    }
}


Output

Geek
GeeksQuiz
Geek2

Important Points/Observations:

Here are some significant points regarding Functional interfaces in Java:

  1. In functional interfaces, there is only one abstract method supported. If the annotation of a 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 functions, that interface will not be called a functional interface. It is called a non-functional interface.
  2. There is no such need for the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking the compiler level. Besides this, it is optional.
  3. An infinite number of methods (whether static or default) can be added to the functional interface. In simple words, there is no limit to a functional interface containing static and default methods.
  4. Overriding methods from the parent class do not violate the rules of a functional interface in Java.
  5. The java.util.function package contains many built-in functional interfaces in Java 8.



Previous Article
Next Article

Similar Reads

Callback using Interfaces in Java
Callback in C/C++ : The mechanism of calling a function from another function is called “callback”. Memory address of a function is represented as ‘function pointer’ in the languages like C and C++. So, the callback is achieved by passing the pointer of function1() to function2().Callback in Java : But the concept of a callback function does not ex
4 min read
Private Methods in Java 9 Interfaces
Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible. Interfaces till Java 7 In Java SE 7 or earlier versions, an interface can have only two things i.e. Constant variables and Abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface. // Java 7 progr
4 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
Generic Constructors and Interfaces in Java
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “&lt;&gt;” after the class name as of the instance variable. Generic constructors are the same as generic methods. For generic constructors after th
5 min read
Interfaces and Polymorphism in Java
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help
6 min read
Which Java Types Can Implement Interfaces?
In Java there is no concept of multiple-inheritance, but with the help of interface we can achieve multiple-inheritance. An interface is a named collection of definition. (without implementation) An interface in Java is a special kind of class. Like classes, interface contains methods and members; unlike classes, in interface all members are final
7 min read
Match Lambdas to Interfaces in Java
One of the most popular and important topics is lambda expression in java but before going straight into our discussion, let us have insight into some important things. Starting off with the interfaces in java as interfaces are the reference types that are similar to classes but containing only abstract methods. This is the definition of interface
5 min read
Types of Interfaces in Java
In Java, an interface is a reference type similar to a class that can contain only constants, the method signatures, default methods, and static methods, and its Nested types. In interfaces, method bodies exist only for default methods and static methods. Writing an interface is similar to writing to a standard class. Still, a class describes the a
6 min read
How to Implement Multiple Inheritance by Using Interfaces in Java?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when methods with the same signature exist in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class
2 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This means that we cannot implement a class from the interf
7 min read
Access modifiers for classes or interfaces in Java
In Java, methods and data members can be encapsulated by the following four access modifiers. The access modifiers are listed according to their restrictiveness order. 1) private (accessible within the class where defined) 2) default or package-private (when no access modifier is specified) 3) protected (accessible only to classes that subclass you
1 min read
Interfaces in Java
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. What are Interfaces in Java?The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface cou
11 min read
Functional Programming in Java with Examples
So far Java was supporting the imperative style of programming and object-oriented style of programming. The next big thing what java has been added is that Java has started supporting the functional style of programming with its Java 8 release. In this article, we will discuss functional programming in Java 8. What is functional programming? It is
9 min read
How to Create Interfaces in Android Studio?
Interfaces are a collection of constants, methods(abstract, static, and default), and nested types. All the methods of the interface need to be defined in the class. The interface is like a Class. The interface keyword is used to declare an interface. public interface AdapterCallBackListener { void onRowClick(String searchText); } public interface
4 min read
Access specifier of methods in interfaces
In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with fields names. Therefore, data fields must be initialized. Consider the following example, x is by default public static final and foo() is public even if there are no specifi
1 min read
Two interfaces with same methods having same signature but different return types
Java does not support multiple inheritances but we can achieve the effect of multiple inheritances using interfaces. In interfaces, a class can implement more than one interface which can't be done through extends keyword. Please refer Multiple inheritance in java for more. Let's say we have two interfaces with same method name (geek) and different
2 min read
Spring Cloud Stream - Functional and Reactive
Spring Cloud Stream is a Spring framework that simplifies creating event-driven microservices. It uses functional programming constructs for message processing logic, often using annotated methods within a class and reactive programming tools like Reactor for asynchronous and reactive processing. Maven Dependencies&lt;dependency&gt; &lt;groupId&gt;
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Article Tags :
Practice Tags :