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:
xxxxxxxxxx
1
Integer[] numbersArray = { 1, 5, 2, 16, -5};
2
3
int max = Collections.max(Arrays.asList(numbersArray));
4
System.out.println( max ); // 16
1. With Collections.max
method
xxxxxxxxxx
1
public class MathExample {
2
3
public static void main(String[] args) {
4
Integer[] numbersArray = { 1, 5, 2, 16, -5};
5
6
int max = Collections.max(Arrays.asList(numbersArray));
7
System.out.println( max ); // 16
8
}
9
}
xxxxxxxxxx
1
public class MathExample {
2
3
static double max(double[] array) {
4
double result = Double.NEGATIVE_INFINITY;
5
for (double currentNumber : array) {
6
if (result < currentNumber) result = currentNumber;
7
}
8
return result;
9
}
10
11
public static void main(String[] args) {
12
double[] numbersArray = {1.4, 5.0, 2.2, 16.0, -5.0};
13
14
System.out.println( max(numbersArray) ); // 16.0
15
}
16
}