Java Function

Introduction

In Java, the Function interface is a functional interface that represents a function that accepts one argument and produces a result. It is part of the java.util.function package and is commonly used for transforming or processing data.

Table of Contents

  1. What is Function?
  2. Methods and Syntax
  3. Examples of Function
  4. Real-World Use Case
  5. Conclusion

1. What is Function?

Function is a functional interface that takes one argument and returns a result. It includes methods for function composition, allowing for chaining multiple operations.

2. Methods and Syntax

The Function interface has several key methods:

  • R apply(T t): Applies this function to the given argument and returns a result.
  • <V> Function<T, V> andThen(Function<? super R, ? extends V> after): Returns a composed function that first applies this function and then applies the after function.
  • <V> Function<V, R> compose(Function<? super V, ? extends T> before): Returns a composed function that first applies the before function and then applies this function.
  • static <T> Function<T, T> identity(): Returns a function that always returns its input argument.

Syntax

Function<T, R> function = (T t) -> {
    // operation on t
    return result;
};

3. Examples of Function

Example 1: Converting a String to Uppercase

import java.util.function.Function;

public class UppercaseExample {
    public static void main(String[] args) {
        // Define a Function that converts a string to uppercase
        Function<String, String> toUpperCase = (str) -> str.toUpperCase();

        String result = toUpperCase.apply("hello");
        System.out.println(result);  // Output: HELLO
    }
}

Example 2: Using andThen

import java.util.function.Function;

public class AndThenExample {
    public static void main(String[] args) {
        // Define a Function that converts a string to uppercase
        Function<String, String> toUpperCase = (str) -> str.toUpperCase();

        // Define another Function that calculates the length of a string
        Function<String, Integer> stringLength = (str) -> str.length();

        // Compose the two functions
        Function<String, Integer> upperCaseThenLength = toUpperCase.andThen(stringLength);

        int length = upperCaseThenLength.apply("hello");
        System.out.println("Length: " + length);  // Output: 5
    }
}

Example 3: Using compose

import java.util.function.Function;

public class ComposeExample {
    public static void main(String[] args) {
        // Define a Function that trims a string
        Function<String, String> trim = (str) -> str.trim();

        // Define a Function that converts a string to uppercase
        Function<String, String> toUpperCase = (str) -> str.toUpperCase();

        // Compose the two functions
        Function<String, String> trimThenUpperCase = toUpperCase.compose(trim);

        String result = trimThenUpperCase.apply("  hello ");
        System.out.println(result);  // Output: HELLO
    }
}

Example 4: Using identity

import java.util.function.Function;

public class IdentityExample {
    public static void main(String[] args) {
        // Use the identity function
        Function<String, String> identityFunction = Function.identity();

        String result = identityFunction.apply("hello");
        System.out.println(result);  // Output: hello
    }
}

4. Real-World Use Case: Formatting and Validating User Input

In applications, Function can be used to format and validate user input, such as trimming whitespace and converting to uppercase.

import java.util.function.Function;

public class UserInputFormatter {
    public static void main(String[] args) {
        // Define a Function to trim whitespace
        Function<String, String> trim = (str) -> str.trim();

        // Define a Function to convert to uppercase
        Function<String, String> toUpperCase = (str) -> str.toUpperCase();

        // Compose functions to trim and then convert to uppercase
        Function<String, String> formatInput = trim.andThen(toUpperCase);

        String formattedInput = formatInput.apply("  user input  ");
        System.out.println("Formatted Input: " + formattedInput);  // Output: USER INPUT
    }
}

Conclusion

The Function interface is a versatile tool in Java for transforming and processing data. It supports function composition through andThen and compose, and provides the identity function for returning inputs as-is. Using Function can lead to cleaner and more efficient code, especially in functional programming contexts.

Comments