Java 8 - IntUnaryOperator interface example

Posted on December 3, 2016


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

Example #1

The following example shows how to use the applyAsInt() method of the IntUnaryOperator interface with lambda expression.

IntUnaryOperatorExample1.java

package com.boraji.tutorial.lambda;

import java.util.function.IntUnaryOperator;

/**
 * @author imssbora
 */
public class IntUnaryOperatorExample1 {
	public static void main(String[] args) {
		IntUnaryOperator operator = a -> a * 10;
		
		System.out.println(operator.applyAsInt(10));
		System.out.println(operator.applyAsInt(12));
	}
}

Output

100
120

Example #2

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

IntUnaryOperatorExample2.java

package com.boraji.tutorial.lambda;

import java.util.function.IntUnaryOperator;

/**
 * @author imssbora
 */
public class IntUnaryOperatorExample2 {
	public static void main(String[] args) {
		IntUnaryOperator operator1 = a -> a * 10;
		IntUnaryOperator operator2 = a -> a * a;

		// Using andThen()
		System.out.println(operator1.andThen(operator2).applyAsInt(10));

		// Using compose()
		System.out.println(operator1.compose(operator2).applyAsInt(10));
	}
}

Output

10000
1000