What is the identity method of the Function interface in Java?

identity is a static method of the Function interface that always returns the input argument.

Syntax

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

Parameters

The method has no parameters.

Return value

The method returns a function that always returns its input argument.

Code

import java.util.function.Function;
public class Main {
public static void main(String[] args){
Function<Integer, Integer> identity = Function.identity();
int arg = 1;
System.out.printf("(%s == identity.apply(%s)) = %s", arg, arg, (arg == identity.apply(arg)));
}
}

Explanation

  • Line 1 - We import the Function interface.
  • Line 6 - We define an identity function using the identity() method.
  • Line 7 - We define an integer called arg.
  • Line 8 - We check whether arg and the value returned are equal. We do this by using the apply() method passing arg as an argument are equal.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources