Java 8 — Binary Operator | Code Factory

Code Factory
1 min readMay 8, 2020

--

Index Page : Link

Reference Link : Link

Donate : Link

  • It is the child of BiFunction<T,T,T>
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
// andThen, apply inherited from interface java.util.function.BiFunction
static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) { }
static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) { }
}

Concat String using BiFunction :

package com.codeFactory.binaryOperator;import java.util.function.BiFunction;public class Test {
public static void main(String... args) {
BiFunction<String, String, String> f = (s1, s2) -> s1 + s2;
System.out.println(f.apply("Code", "Factory"));
}
}

Output :

CodeFactory

Concat String using BinaryOperator :

package com.codeFactory.binaryOperator;import java.util.function.BinaryOperator;public class Test {
public static void main(String... args) {
BinaryOperator<String> b = (s1, s2) -> s1 + s2;
System.out.println(b.apply("Code", "Factory"));
}
}

Output :

CodeFactory

The primitive versions for BinaryOperator :

1. IntBinaryOperator

@FunctionalInterface
public interface IntBinaryOperator {
int applyAsInt(int left, int right);
}

2. LongBinaryOperator

@FunctionalInterface
public interface LongBinaryOperator {
long applyAsLong(long left, long right);
}

3. DoubleBinaryOperator

@FunctionalInterface
public interface DoubleBinaryOperator {
double applyAsDouble(double left, double right);
}

Example 1 :

package com.codeFactory.binaryOperator;import java.util.function.BinaryOperator;public class Test {
public static void main(String... args) {
BinaryOperator<Integer> b = (i1, i2) -> i1 + i2;
System.out.println(b.apply(10, 20));
}
}

Output :

30

Example 2 :

package com.codeFactory.binaryOperator;import java.util.function.IntBinaryOperator;public class Test {
public static void main(String... args) {
IntBinaryOperator i = (i1, i2) -> i1 + i2;
System.out.println(i.applyAsInt(10, 20));
}
}

Output :

30

--

--