How to implement IntUnaryOperator using lambda in Java?

IntUnaryOperator represents a functional interface that takes an int value and returns another int value. It is defined in java.util.function package and used as an assignment target for a lambda expression or method reference. It contains one abstract method: applyAsInt(), two default methods: compose(), andThen() and one static method: identity().


public interface IntUnaryOperator


import java.util.function.IntUnaryOperator;

public class IntUnaryOperatorLambdaTest1 {
   public static void main(String[] args) {
      IntUnaryOperator getSquare = intValue -> {    // lambda expression
         int result = intValue * intValue;
         System.out.println("Getting square: "+ result);
         return result;
      IntUnaryOperator getNextInt = intValue -> {   // lambda expression
         int result = intValue+1;
         System.out.println("Getting Next Int: "+ result);
         return result;
      IntUnaryOperator getSquareOfNext = getSquare.andThen(getNextInt);
      IntUnaryOperator getNextOfSquare = getSquare.compose(getNextInt);

      int input = 3;
      System.out.println("Input int value: "+ input);

      int squareOfNext = getSquareOfNext.applyAsInt(input);
      System.out.println("Square of next int value: "+ squareOfNext);

      int nextOfSquare = getNextOfSquare.applyAsInt(input);
      System.out.println("Next to square of int value: "+ nextOfSquare);


Input int value : 3

Getting square : 9
Getting Next Int : 10
Square of next int value : 10

Getting Next Int : 4
Getting square : 16
Next to square of int value : 16


import java.util.concurrent.ThreadLocalRandom;
import java.util.function.IntUnaryOperator;

public class IntUnaryOperatorLambdaTest2 {
   public static int getRandonInt(){
      return ThreadLocalRandom.current().nextInt(1000, 4999);
   public static void main(String[] args) {
      IntUnaryOperator getInput = IntUnaryOperator.identity();
      int identityVal = getInput.applyAsInt(getRandonInt());
      System.out.println("Value passed as argument: "+ identityVal);
      System.out.println("Value passed as argument: "+ getInput.applyAsInt(getRandonInt()));
      System.out.println("Value passed as argument: "+ getInput.applyAsInt(getRandonInt()));


Value passed as argument: 3141
Value passed as argument: 2635
Value passed as argument: 1179

Updated on: 13-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started