How to implement LongUnaryOperator using lambda in Java?


LongUnaryOperator is a functional interface from java.util.function package. This functional interface accepts a single long-valued operand and produces a long-valued result. LongUnaryOperator interface can be used as an assignment target for lambda expression and method reference. It contains one abstract method: applyAsLong(), one static method: identity() and two default methods: andThen() and compose().

Syntax

@FunctionalInterface
public interface LongUnaryOperator
 long applyAsLong(long operand);
}

Example

import java.util.function.LongUnaryOperator;

public class LongUnaryOperatorTest {
   public static void main(String args[]) {
      LongUnaryOperator getSquare = longValue -> {       // lambda
         long result = longValue * longValue;
         System.out.println("Getting square: " + result);
         return result;
      };
      LongUnaryOperator getNextValue = longValue -> {      // lambda
         long result = longValue + 1;
         System.out.println("Getting Next value: " + result);
         return result;
      };
      LongUnaryOperator getSquareOfNext = getSquare.andThen(getNextValue);
      LongUnaryOperator getNextOfSquare = getSquare.compose(getNextValue);

      long input = 10L;
      System.out.println("Input long value: " + input);
      System.out.println();

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

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

Output

Input long value: 10

Getting square: 100
Getting Next value: 101
Square of next value: 101

Getting Next value: 11
Getting square: 121
Next to square of value: 121

Updated on: 14-Jul-2020

94 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements