DEV Community

Apurv
Apurv

Posted on • Originally published at apurvsheth.Medium on

Java — Functional Interface

Java — Functional Interface

Introduction

The reason it’s called a “functional interface” is that it effectively acts like a function. Since you can pass interfaces as parameters, it means that functions are now “first-class citizens” like in functional programming languages. This has many benefits, and you’ll see them quite a lot when using the Java Stream API. Of course, lambda expressions are the main use for them.

Here, we will go through the different functional interfaces introduced in java 8.

Consumer

  • It is an inbuild functional interface introduced in java 8.
  • It can be used where objects can be consumed, perform some operations & don’t require to send back output.
  • Contract

‘’’

/**

* perform this operation on the given argument.

* @param t — input

* return — void

*/

void accept(T t)

‘’’

Predicate

  • This functional interface is mainly used for conditional checks.
  • We can use this where the functionality requires to return boolean.
  • Contract

/**

* Evaluates the pridicate on the given argument.

* @param t — input

* return — boolean

*/

boolean test(T t)

  • Example:

import java.util.*;

import java.util.function.Predicate;

class HelloPridicate {

public static void main(String args[])

{

// create a list of strings

List str = Arrays.asList(“apurv”, “sheth”, “paras”, “test”, “pridicate”);

// declare the predicate type as string and use lambda expression to create object

Predicate p = (s) -> s.startsWith(“p”);

// Iterate through the list

for (String st : str) {

// call the test method

if (p.test(st))

System.out.println(st);

}

}

}

Output:

paras

pridicate

Supplier

  • It can be used where there are no inputs required & only output is expected.
  • Contract :

/**

* To get a result.

* @return — result

*/

T get();

Key take away :

Here are some key take away w.r.t. Functional interfaces in Java:

  1. The java.util.function package contains many built-in functional interfaces in Java 8.
  2. It is not mandatory to use @FunctionalInterface annotation. it just helps in checking the compiler level otherwise it’s optional.
  3. Any number of methods, whether static or default, can be added to the functional interface. There is no limit to a functional interface containing static and default methods.
  4. The functional interface supports only a single abstract method. 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.
  5. 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.
  6. Overriding methods from the parent class do not violate the rules of a functional interface.

GitHub Repo:- https://github.com/shethaptech/java

Top comments (0)