Java Function identity()

In this guide, you will learn about the Function identity() method in Java programming and how to use it with an example.

1. Function identity() Method Overview

Definition:

The Function.identity() method is a static utility method that returns a function that always returns its input argument. In simpler terms, it's a function where the output is always the same as the input.

Syntax:

static <T> Function<T, T> identity()

Parameters:

None.

Key Points:

- It's often used in scenarios where a function is expected, but you want to make no changes to the data.

- Commonly utilized in Java Streams, especially with methods like map() when no transformation is required.

- It returns a singleton instance.

2. Function identity() Method Example

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

public class FunctionIdentityExample {
    public static void main(String[] args) {
        List<String> names = Stream.of("John", "Jane", "Jack", "Jill")
                                   .map(Function.identity())  // No transformation, just pass the same element
                                   .collect(Collectors.toList());

        System.out.println("Names after applying identity function: " + names);
    }
}

Output:

Names after applying identity function: [John, Jane, Jack, Jill]

Explanation:

In the provided example, we create a stream of names and then apply the Function.identity() using the map() function. Since the identity() function does not transform the data, the names remain unchanged. It's used here to demonstrate its use, but in practical scenarios, if no transformation is needed, you can omit the map() operation altogether.

Comments