25. Computing the minimum and maximum of two numbers

Before JDK 8, a possible solution would be to rely on the Math.min() and Math.max() methods, as follows:

int i1 = -45;
int i2 = -15;
int min = Math.min(i1, i2);
int max = Math.max(i1, i2);

The Math class provides a min() and a max() method for each primitive numeric type (int, long, float, and double).

Starting with JDK 8, each wrapper class of primitive numeric types (Integer, Long, Float, and Double) comes with dedicated min() and max() methods, and, behind these methods, there are invocations of their correspondents from the Math class. See the following example (this is a little bit more expressive):

double d1 = 0.023844D;
double d2 = 0.35468856D;
double min = Double.min(d1, d2);
double max = Double.max(d1, d2);

In a functional style context, a potential solution will rely on the BinaryOperator functional interface. This interface comes with two methods, minBy() and maxBy()

float f1 = 33.34F;
final float f2 = 33.213F;
float min = BinaryOperator.minBy(Float::compare).apply(f1, f2);
float max = BinaryOperator.maxBy(Float::compare).apply(f1, f2);

These two methods are capable of returning the minimum (respectively, the maximum) of two elements according to the specified comparator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.197.136