Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
unaryoperator
communitycreator

What is the UnaryOperator functional interface in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

UnaryOperator is a functional interface that represents a single-operand operation which yields a result of the same type as the operand.

The interface extends the Function interface so the methods of the Function interface can be used on the implementation of the UnaryOperator interface. The interface overrides the identity() method of the Function interface.

The UnaryOperator interface is defined in the java.util.function package. To import the UnaryOperator interface, use the following import statement:

import java.util.function.UnaryOperator;
Import statement

What is the identity() method?

The identity() method is a static method used to return a unaryOperator that always returns its input argument.

Syntax

static <T> UnaryOperator<T> identity()
Syntax

Parameters

The method has no parameters.

Return value

This method returns the input argument.

Example

import java.util.function.UnaryOperator;
public class Main{
public static void main(String[] args) {
// Identity unary operator that accepts one input
UnaryOperator<Integer> unaryOperator = UnaryOperator.identity();
// argument
int arg = 3;
System.out.printf("UnaryOperator.identity(%s) = %s", arg, unaryOperator.apply(3));
}
}
Implementation of identity() method

Explanation

  • Line 1: We import the relevant packages.
  • Line 8: We define an identity unaryOperator that accepts one input of integer type.
  • Line 11: We define an integer value.
  • Line 13: We test the identity unaryOperator using the apply() method on the integer value defined in line 11 and print the result.

RELATED TAGS

java
unaryoperator
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring