Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

8.2. Finding the Maximum and Minimum in an Array

8.2.1. Problem

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

8.2.2. 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

8.2.3. 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.

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 );

Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.