Java 8 Functional Interfaces

by:

Uncategorized

A functional interface is an interface that contains (must contain) one and 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
  • @FunctionalInterface annotation is used to ensure an interface can’t have more than one abstract method. The use of this annotation is optional
  • The Java.util.function package contains many builtin functional interfaces in Java 8

Some of builtin functional interfaces are described below :

@FunctionalInterface

public interface Predicate<T> {

    boolean test(T t);

}

Represents a predicate (boolean-valued function) of one argument. Example of using Predicate :

Predicate<String> predicate = str -> str.isEmpty();
System.out.println(predicate.test("")); //true

 

@FunctionalInterface

public interface Function<T, R> {

    public <R> apply(T parameter);

}

Represents a function (method) that takes a single parameter and returns a single value. Example of using Function :

Function<String, Integer> function = str -> Integer.valueOf(str);
System.out.println(function.apply("123")); //123

 

@FunctionalInterface

public interface Supplier<T> {

    public T get();

}

Represents a function that supplies a value of some sorts. Supplier interface can also be thought of as a factory interface. Example of using Supplier :

Supplier<String> supplier = () -> "Hello, " + "World";
System.out.println(supplier.get()); //Hello, World

@FunctionalInterface

public interface Consumer<T> {

    public void accept(T t);

}

Represents a function that consumes a value without returning any value. Example of using Consumer :

Consumer<Integer> consumer = (value) -> System.out.println("Reported Integer is " + value);
consumer.accept(25); // Reported Integer is 25

@FunctionalInterface

public interface UnaryOperator<T> extends Function<T, T>{

}

Represents an operation which takes a single parameter and returns parameter of the same type. UnaryOperator extends Function interface. What distinguishes it from a normal Function is that both its argument and return type are the same. Example of using UnaryOperator :

UnaryOperator<Integer> func1 = x -> x + 2;
UnaryOperator<Integer> func2 = x -> x * 3;
System.out.println(func1.andThen(func2).apply(3)); //15

Leave a Reply

Your email address will not be published. Required fields are marked *