EN
Java - max value in array
0
points
This article will show you how to find the maximum value in an array in Java.
Quick solution:
Integer[] numbersArray = { 1, 5, 2, 16, -5};
int max = Collections.max(Arrays.asList(numbersArray));
System.out.println( max ); // 16
Practical examples
1. With Collections.max
method
public class MathExample {
public static void main(String[] args) {
Integer[] numbersArray = { 1, 5, 2, 16, -5};
int max = Collections.max(Arrays.asList(numbersArray));
System.out.println( max ); // 16
}
}
2. By comparing all the elements in the array
public class MathExample {
static double max(double[] array) {
double result = Double.NEGATIVE_INFINITY;
for (double currentNumber : array) {
if (result < currentNumber) result = currentNumber;
}
return result;
}
public static void main(String[] args) {
double[] numbersArray = {1.4, 5.0, 2.2, 16.0, -5.0};
System.out.println( max(numbersArray) ); // 16.0
}
}