Java 8 – Binary Operator | Code Factory


Index Page : Link

Donate : Link

Medium Blog : Link

Applications : 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

One thought on “Java 8 – Binary Operator | Code Factory”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s