Predefined Functional Interface in Java 8

Java provides a bunch of predefined functional interfaces that come under java.util.function package. Each and every predefined functional interface has its own characteristics. Some of the major ones are : predicate, consumer, supplier and function.

Predicate

– It accepts a single input and always returns a boolean value as an output
– In other words, it is used for conditional checks
– It supports a single abstract method named test()
– it always return a boolean type

For example:

import java.util.function.Predicate;

public class InBuiltFunctionalInterfaceExamples {

    public static void main(String[] args) {
        Predicate<Integer> ageTester = (x) -> x>18;
        if(ageTester.test(15))
        {
            System.out.println("You can vote");
        }
        else
        {

            System.out.println("You are too young");
        }
    }
}

Output:

You are too young

 

Function

– It is used for performing logic on given input.
– It takes two arguments first is to represent input and second is for output.
– It supports a single abstract method named apply()
– Its return type can be varied

For example:

import java.util.function.Function;

public class InBuiltFunctionalInterfaceExamples {

    public static void main(String[] args) {
        Function<Integer,Integer> calculator = (x) -> 4*4;
        System.out.println("Square : "+calculator.apply(4));
    }
}

Output:

Square: 16

Function chaining: Combining two or more functions to form more complex function is known as function chaining.

 

Consumer

– It accepts a single input argument but returns nothing
– It supports a single abstract method named accept()
– It doesn’t have any return type

For example:

import java.util.function.Consumer;

public class InBuiltFunctionalInterfaceExamples {

    public static void main(String[] args) {
        Consumer<Integer> display = (x) -> System.out.println("I am displaying "+ x);
       display.accept(10);
    }
}

Output:

I am displaying 10

 

Supplier

– It accepts no argument but returns a value
– It must return something
– It supports a single abstract method named get()

For example:

import java.util.Date;
import java.util.function.Supplier;

public class InBuiltFunctionalInterfaceExamples {

    public static void main(String[] args) {
        Supplier<Date> date = () -> new Date();
        System.out.println("Date : "+date.get());

    }
}

Output:

Date : Mon Jun 15 16:31:22 IST 2020

Other functional Interfaces

There are more predefined functional interfaces:-

  • Interfaces that accepts two arguments:
    -BiFunction
    -BiPredicate
    -BiConsumer
  •  Interfaces that accept a specific datatype:
    DoubleSupplier
    DoubleConsumer
    IntPredicate
    IntSupplier
    and more
  • Other intefaces are BinaryOperator, UnaryOperator

Leave a Reply