0
0
JavaHow-ToBeginner · 3 min read

How to Use Function Interface in Java: Syntax and Examples

In Java, Function is a functional interface used to represent a function that takes one argument and produces a result. You use it by implementing its apply() method, often with a lambda expression, to transform input data into output.
📐

Syntax

The Function interface is part of java.util.function package. It has one abstract method apply() that takes an input and returns an output.

Syntax parts:

  • Function<T, R>: T is the input type, R is the output type.
  • apply(T t): method to transform input t to output.
java
import java.util.function.Function;

Function<T, R> function = (T t) -> {
    // transform t and return result of type R
    return null; // placeholder return
};
💻

Example

This example shows how to use Function to convert a string to its length.

java
import java.util.function.Function;

public class FunctionExample {
    public static void main(String[] args) {
        Function<String, Integer> stringLength = s -> s.length();

        String input = "Hello, Java!";
        int length = stringLength.apply(input);

        System.out.println("Length of '" + input + "' is: " + length);
    }
}
Output
Length of 'Hello, Java!' is: 12
⚠️

Common Pitfalls

Common mistakes when using Function include:

  • Not matching input and output types correctly.
  • Forgetting to import java.util.function.Function.
  • Trying to use Function for methods with multiple inputs (use BiFunction instead).
java
import java.util.function.Function;

// Wrong: input and output types mismatch
// Function<String, Integer> f = s -> s.toUpperCase(); // Error: returns String, not Integer

// Right:
Function<String, String> f = s -> s.toUpperCase();
📊

Quick Reference

  • Function<T, R>: takes input T, returns R.
  • apply(T t): method to execute the function.
  • Use lambdas for concise function definitions.
  • For two inputs, use BiFunction.
  • Functions can be composed with andThen() and compose().

Key Takeaways

Use the Function interface to represent a function that takes one input and returns a result.
Implement Function with a lambda expression for simple and readable code.
Always match the input and output types correctly in Function.
For multiple inputs, use BiFunction instead of Function.
Use Function's default methods like andThen() to chain functions.