0Pricing
Java Academy · Lesson

Function and BiFunction

Transform values functionally.

What Function Represents

Function<T, R> is the core transformation interface in java.util.function. It takes one argument of type T and returns a result of type R.

  • Its single abstract method is R apply(T t).
  • It models a pure mapping from input to output.
import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<String, Integer> length = s -> s.length();
        System.out.println(length.apply("hello"));
    }
}

Calling apply

You invoke a Function by calling apply. The lambda body is the transformation logic.

  • Input and output types can differ.
  • A method reference like String::toUpperCase can replace a lambda.
import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<String, String> upper = String::toUpperCase;
        System.out.println(upper.apply("java"));
    }
}

All lessons in this course

  1. Function and BiFunction
  2. Supplier and Consumer
  3. Predicate and Composition
  4. Custom Functional Interfaces
← Back to Java Academy