How do I use the Function functional interface in Java?

The Function interface is part of the java.util.function package and represents a single argument function that produces a result. It is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

Here’s the function signature:

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

It defines:
T: Type of the input.
R: Type of the result.


How to Use the Function Interface

1. Using a Lambda Expression

We can implement the apply method using a lambda expression to define custom operations like converting or transforming data:

Example:

package org.kodejava.util.function;

import java.util.function.Function;

public class FunctionExample {
    public static void main(String[] args) {
        // Define a Function to calculate the length of a string
        Function<String, Integer> lengthFunction = s -> s.length();

        // Apply the function
        String input = "Hello, World!";
        Integer length = lengthFunction.apply(input);

        System.out.println("The length of the string is: " + length);
    }
}

Here, the input string’s length is calculated using the lambda.


2. Using Method References

We can use method references to utilize predefined methods with the Function interface.

Example:

package org.kodejava.util.function;

import java.util.function.Function;

public class MethodReferenceExample {
    public static void main(String[] args) {
        // Use Function to convert a string to uppercase
        Function<String, String> toUpperCaseFunction = String::toUpperCase;

        // Apply the function
        String input = "hello";
        String result = toUpperCaseFunction.apply(input);

        System.out.println("Uppercase: " + result);
    }
}

Here, the String::toUpperCase method is referenced as the function.


3. Chaining Functions

The Function interface has default methods like andThen and compose for combining functions.

  • andThen: Executes the current function, then another.
  • compose: Executes another function first, then the current one.

Example:

package org.kodejava.util.function;

import java.util.function.Function;

public class FunctionChainingExample {
    public static void main(String[] args) {
        // Convert a string to uppercase
        Function<String, String> toUpperCaseFunction = String::toUpperCase;

        // Add a prefix
        Function<String, String> addPrefixFunction = s -> "Prefix: " + s;

        // Chain the functions
        Function<String, String> combinedFunction = toUpperCaseFunction.andThen(addPrefixFunction);

        // Apply the combined function
        String result = combinedFunction.apply("hello");

        // Output: Prefix: HELLO
        System.out.println(result);
    }
}

4. Using Function with Streams

The Function interface fits naturally into stream operations like map.

Example:

package org.kodejava.util.function;

import java.util.function.Function;
import java.util.stream.Stream;

public class StreamFunctionExample {
    public static void main(String[] args) {
        // Create a stream of numbers as strings
        Stream<String> numberStream = Stream.of("1", "2", "3");

        // Convert numbers from String to Integer
        Function<String, Integer> parseIntFunction = Integer::parseInt;

        // Use Function in map operation
        // Output: 1, 2, 3
        numberStream.map(parseIntFunction)
                .forEach(System.out::println);
    }
}

Here, the Function is used to transform the stream’s items.


Summary

  • The Function interface is a generic functional interface with a single method, apply, for transforming objects.
  • It supports lambdas, method references, and function chaining with andThen and compose.
  • It is commonly used in stream transformations.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.