Finding the max/min value in an array of primitives using Java
To find the maximum value in an array of primitives in Java, you can use the Arrays.stream()
method to create a stream from the array, and then use the Stream.max()
method to find the maximum element in the stream. Here is an example of how to do this for an array of int
values:
int[] values = {3, 5, 2, 8, 1};
int max = Arrays.stream(values).max().getAsInt();
To find the minimum value, you can use the Stream.min()
method instead. Here is an example for an array of double
values:
double[] values = {3.5, 5.1, 2.7, 8.9, 1.2};
double min = Arrays.stream(values).min().getAsDouble();
Note that these examples use the getAsInt()
and getAsDouble()
methods to get the maximum and minimum values from the optional returned by max()
and min()
, respectively. This is because these methods may return an empty optional if the stream is empty.
If you are using an older version of Java that does not support the Stream
API, you can use a loop to iterate over the array and keep track of the maximum and minimum values as you go. Here is an example of how to do this for an array of int
values:
int[] values = {3, 5, 2, 8, 1};
int max = values[0];
int min = values[0];
for (int i = 1; i < values.length; i++) {
max = Math.max(max, values[i]);
min = Math.min(min, values[i]);
}
You can use a similar approach for other primitive data types, such as double
, float
, etc. Just make sure to use the appropriate method from the Math
class (such as Math.max()
or Math.min()
) to compare the values.