Finding the max/min value in an array of primitives using Java
Using Commons Lang (to convert) + Collections (to min/max)
import java.util.Arrays;import java.util.Collections;import org.apache.commons.lang.ArrayUtils;public class MinMaxValue { public static void main(String[] args) { char[] a = {'3', '5', '1', '4', '2'}; List b = Arrays.asList(ArrayUtils.toObject(a)); System.out.println(Collections.min(b)); System.out.println(Collections.max(b)); }}
Note that Arrays.asList()
wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.
You can simply use the new Java 8 Stream
s but you have to work with int
.
The stream
method of the utility class Arrays
gives you an IntStream
on which you can use the min
method. You can also do max
, sum
, average
,...
The getAsInt
method is used to get the value from the OptionalInt
import java.util.Arrays;public class Test { public static void main(String[] args){ int[] tab = {12, 1, 21, 8}; int min = Arrays.stream(tab).min().getAsInt(); int max = Arrays.stream(tab).max().getAsInt(); System.out.println("Min = " + min); System.out.println("Max = " + max) }}
==UPDATE==
If execution time is important and you want to go through the data only once you can use the summaryStatistics()
method like this
import java.util.Arrays;import java.util.IntSummaryStatistics;public class SOTest { public static void main(String[] args){ int[] tab = {12, 1, 21, 8}; IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics(); int min = stat.getMin(); int max = stat.getMax(); System.out.println("Min = " + min); System.out.println("Max = " + max); }}
This approach can give better performance than classical loop because the summaryStatistics
method is a reduction operation and it allows parallelization.
The Google Guava library has min and max methods in its Chars, Ints, Longs, etc. classes.
So you can simply use:
Chars.min(myarray)
No conversions are required and presumably it's efficiently implemented.