Java 8 - BinaryOperator interface example

Posted on November 27, 2016


java.util.function.BinaryOperator is a functional interface, which extends the java.util.function.BiFunction interface . The BinaryOperator interface represents an operation that takes two arguments of same type and returns a result of same type as its input arguments.

Note – The BinaryOperator interface inherits the functional method apply() and default method andThen() from  the BiFunction interface.

Example #1

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

BinaryOperatorExample1.java

package com.boraji.tutorial.lambda;

import java.util.function.BinaryOperator;

/**
 * @author imssbora
 */
public class BinaryOperatorExample1 {
	public static void main(String[] args) {
		BinaryOperator<Integer> operator1 = (a, b) -> a + b;
		System.out.println(operator1.apply(5, 7));

		BinaryOperator<String> operator2 = (s1, s2) -> s1 + s2;
		System.out.println(operator2.apply("Hello ", "BORAJI.COM"));
	}
}

Output

12
Hello BORAJI.COM

 

Example #2

The following example shows how to use the default method andThen() of the BinaryOperator interface with lambda expression.

package com.boraji.tutorial.lambda;

import java.util.function.BinaryOperator;
import java.util.function.Function;

/**
 * @author imssbora
 */
public class BinaryOperatorExample2 {
	public static void main(String[] args) {
		BinaryOperator<Integer> operator = (a, b) -> a + b;
		Function<Integer, Integer> function = n -> n * 2;

		// Using andThen()
		System.out.println(operator.andThen(function).apply(1, 6));

	}
}

Output

14

Example #3

The following example shows how to use the static methods maxBy()  and minBy() of the BinaryOperator interface with lambda expression.

package com.boraji.tutorial.lambda;

import java.util.Comparator;
import java.util.function.BinaryOperator;

/**
 * @author imssbora
 */
public class BinaryOperatorExample3 {
	public static void main(String[] args) {

		Comparator<Integer> comparator = (a, b) -> (a.compareTo(b));

		// Using maxBy()
		BinaryOperator<Integer> opMax = BinaryOperator.maxBy(comparator);
		System.out.println("Max: " + opMax.apply(5, 6));
		System.out.println("Max: " + opMax.apply(9, 6));

		// Using minBy()
		BinaryOperator<Integer> opMin = BinaryOperator.minBy(comparator);
		System.out.println("Min: " + opMin.apply(5, 6));
		System.out.println("Min: " + opMin.apply(9, 6));
	}
}

Output

Max: 6
Max: 9
Min: 5
Min: 6