8.2. Finding the Maximum and Minimum in an Array

Problem

You need to retrieve the maximum and minimum values from a double[], float[], long[], int[], short[], or byte[].

Solution

Use Commons Lang NumberUtils.max( ) and NumberUtils.min( ) to retrieve the minimum or maximum values from an array of primitives. The following code retrieves the minimum and maximum values from a double[]:

import org.apache.commons.lang.math.NumberUtils;

double[] array = {0.2, 0.4, 0.5, -3.0, 4.223, 4.226};

double max = NumberUtils.max( array ); // returns 4.226
double min = NumberUtils.min( array ); // returns -3.0

Discussion

NumberUtils.min( ) and NumberUtils.max() both accept double[], float[], long[], int[], short[], and byte[]. If the array is empty or null, both NumberUtils.min( ) and NumberUtils.max( ) will return an IllegalArgumentException.

Jakarta Commons Math also contains a class that can find the minimum and maximum value in a double[]. The following example uses the Max and Min classes from Commons Math to evaluate a double[]:

import 
org.apache.commons.math.stat.univariate.rank.Max;

import org.apache.commons.math.stat.univariate.rank.Min;

double[] array = {0.2, 0.4, 0.5, -3.0, 4.223, 4.226};

Max maximum = new Max( );

Min minimum = new Min( );

double max = maximum.evaluate( array, 0, array.length );

double min = minimum.evaluate( array, 0, array.length );

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.