Using java.util.function.BinaryOperator to create function to return maximum and minimum value in functional programming way
Author : Anurag Anand
You can read first part of this article here .
We all have implemented methods to get maximum or minimum between two different values. A value can be anything, it can be a primitive or an object. It can be an integer or a string or a person object.
We were doing this in an imperative ways. like this.
Maximum function using Imperative way, uses If-Else statement.
private static int maximumWithIfElse(int num1, int num2) {
int max = num2;
if(max < num1) {
max = num1;
}
return max;
}
Maximum function imperative way, uses ternary operator
private static int maximum(int num1, int num2){
return num1 > num2 ? num1 : num2;
}
Minimum function using Imperative way, uses If-Else statement
private static int minimumWithIfElse(int num1, int num2) {
int min = num2;
if(min > num1) {
min = num1;
}
return min;
}
Minimum function using Imperative way, uses ternary operator
private static int minimum(int num1, int num2) {
return num1 < num2 ? num1 : num2;
}
All of the above statements are small and does their job.
We can use the static methods provided by BinaryOperator to achieve the same
Maximum function using functional programming.
BinaryOperator<Integer> maxInteger = BinaryOperator.maxBy(Integer::compareTo);
Minimum function using functional programming.
BinaryOperator<Integer> minInteger = BinaryOperator.minBy(Integer::compareTo);
If we compare the imperative style and functional style. We can see the functional code is much more readable and concise.
This is a very small example, it can be used to create max and min functions for any object, given that object implements comparable interface.
Complete Code
import java.util.function.BinaryOperator;
import static java.lang.System.out;
public class BinaryOperatorMinByAndMaxBy{
public static void main(String ... args){
int num1 = 10;
int num2 = 1;
BinaryOperator<Integer> minInteger = BinaryOperator.minBy(Integer::compareTo);
out.println("Minimum := " + minInteger.apply(num1, num2));
BinaryOperator<Integer> maxInteger = BinaryOperator.maxBy(Integer::compareTo);
out.println("Maximum := " + maxInteger.apply(num1, num2));
}
private static int maximumWithIfElse(int num1, int num2) {
int max = num2;
if(max < num1) {
max = num1;
}
return max;
}
private static int minimumWithIfElse(int num1, int num2) {
int min = num2;
if(min > num1) {
min = num1;
}
return min;
}
private static int maximum(int num1, int num2){
return num1 > num2 ? num1 : num2;
}
private static int minimum(int num1, int num2) {
return num1 < num2 ? num1 : num2;
}
}
Output:-
Minimum := 1
Maximum := 10
Thanks for reading. I really hope, that this article was helpful to you. :)