How to implement IntUnaryOperator using lambda in Java?

Java 8Object Oriented ProgrammingProgramming

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

Syntax

@FunctionalInterface
public interface IntUnaryOperator

Example

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);
      System.out.println();

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

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

Output

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


Example-2

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

Output

Value passed as argument: 3141
Value passed as argument: 2635
Value passed as argument: 1179
raja
Published on 10-Jan-2020 09:38:46
Advertisements