Java - Function interface default and static methods

Introduction

The Function interface contains the following default and static methods:

default <V> Function<T,V> andThen(Function<? super R,? extends V> after)
default <V> Function<V,R> compose(Function<? super V,? extends T> before)
static <T> Function<T,T> identity()

andThen() method returns a composed Function that combines this function and after function.

compose() function returns a composed function that applies the before function, and then applies this function to the result.

identify() method returns a function that always returns its argument.

The following code demonstrates how to use default and static methods of the Function interface to compose new functions:

Demo

import java.util.function.Function;

public class Main {
  public static void main(String[] args) {
    // Create two functions
    Function<Long, Long> square = x -> x * x;
    Function<Long, Long> addOne = x -> x + 1;

    // Compose functions from the two functions
    Function<Long, Long> squareAddOne = square.andThen(addOne);
    Function<Long, Long> addOneSquare = square.compose(addOne);

    // Get an identity function
    Function<Long, Long> identity = Function.<Long>identity();

    // Test the functions
    long num = 5L;
    System.out.println("Number : " + num);
    System.out.println("Square and then add one: " + squareAddOne.apply(num));
    System.out.println("Add one and then square: " + addOneSquare.apply(num));
    System.out.println("Identity: " + identity.apply(num));
  }//  w w  w .ja  v a  2s .c  o m
}

Result

Related Topic