Java 8 - LongUnaryOperator interface example

Posted on April 11, 2017


java.util.function.LongUnaryOperator is a functional interface whose functional method is  long applyAsLong(). The LongUnaryOperator is interface represents an operation that takes a single argument of long type and returns a result of long type.

The following example shows how to use the applyAsLong() method of the LongUnaryOperator is interface with lambda expression.

LongUnaryOperatorExample1.java

package com.boraji.tutorial.lambda;

import java.util.function.LongUnaryOperator;

/**
 * @author imssbora
 */
public class LongUnaryOperatorExample1 {
   public static void main(String[] args) {
      LongUnaryOperator operator = (l) -> l * l;
      System.out.println(operator.applyAsLong(45l));
      System.out.println(operator.applyAsLong(100l));
   }
}

Output

2025
10000

The following example shows how to use the default methods andThen() and compose() of the LongUnaryOperator interface with lambda expression.

LongUnaryOperatorExample2.java

package com.boraji.tutorial.lambda;

import java.util.function.LongUnaryOperator;

/**
 * @author imssbora
 */
public class LongUnaryOperatorExample2 {
   public static void main(String[] args) {
      LongUnaryOperator operator1 = (l) -> l + 10;
      LongUnaryOperator operator2 = (l) -> l * 2;

      // Using default method andThen()
      System.out.println(operator1.andThen(operator2).applyAsLong(10));
      System.out.println(operator2.andThen(operator1).applyAsLong(10));
      
      //Using default method compose()
      System.out.println(operator1.compose(operator2).applyAsLong(10));
      System.out.println(operator2.compose(operator1).applyAsLong(10));
   }
}

Output

40
30
30
40