Trusted answers to developer questions

What is the UnaryOperator functional interface in Java?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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;

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()

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));
}
}

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
Did you find this helpful?