Java - Function<T,R> Interface

Introduction

There are six specializations of the Function<T, R> interface.

IntFunction<R>
LongFunction<R>
DoubleFunction<R>
ToIntFunction<T>
ToLongFunction<T>
ToDoubleFunction<T>

IntFunction<R>, LongFunction<R>, and DoubleFunction<R> take an int, a long, and a double as an argument, respectively, and return a value of type R.

ToIntFunction<T>, ToLongFunction<T>, and ToDoubleFunction<T> take an argument of type T and return an int, a long, and a double, respectively.

The following code shows how to use Function<T, R> function type:

Demo

import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.ToIntFunction;
import java.util.function.UnaryOperator;

public class Main {
  public static void main(String[] args) {
    // Takes an int and returns its square
    Function<Integer, Integer> square1 = x -> x * x;
    IntFunction<Integer> square2 = x -> x * x;
    ToIntFunction<Integer> square3 = x -> x * x;
    UnaryOperator<Integer> square4 = x -> x * x;

    System.out.println(square1.apply(5));
    System.out.println(square2.apply(5));
    System.out.println(square3.applyAsInt(5));
    System.out.println(square4.apply(5));
  }/*from ww w  .j  a va  2 s  . c om*/
}

Result

Related Topics

Example