In this blog post, I will show you the different ways to implement java.util.function.IntBinaryOperator.
You can watch my youtube video, where I code these implementation.
A Regular Class..
private class RegularImpl implements IntBinaryOperator{ @Override public int applyAsInt(final int firstIntValue, final int secondIntValue){ return firstIntValue > secondIntValue ? firstIntValue : secondIntValue; } }
Implementation using a regular class is the same way of implementation that we have always been doing in Java.
Implementation using an anonymous class
private IntBinaryOperator sum = new IntBinaryOperator() { @Override public int applyAsInt(final int firstValue, final int secondValue){ return firstValue + secondValue; } };
The anonymous way of implementing an interface is the same old way. Where we create an instance, and we provide implementation in the curly braces.
Now, we take a look at Lambda implementation
private IntBinaryOperator sumLam_1 = (int firstValue, int secondValue) -> { return firstValue + secondValue; };
The above implementation looks like a function without any name. It is a hybrid between a variable declaration and a function definition.
In next Lambda implementation, we can remove the data-type of the variables. As, compiler is able to figure out the data-type of these parameters from the function declaration of applyAsInt inside the IntBinaryOperator.
private IntBinaryOperator sumLam_2 = (firstValue, secondValue) -> firstValue + secondValue;
The next implementation uses method reference, where we use Class or Instance name followed by :: and name of the method.
private IntBinaryOperator sumLam_3 = Integer::sum;
The above implementation is not a fresh implementation, it delegates all calls to sum method in Integer class.