To find the largest number in an array in Java, call the
Stream.max
method, then getAsInt
.1. With streams
The shortest way is to use streams:
int[] array = new int[] { 400, 55, 3, 90 };
int max = Arrays.stream(array).max().getAsInt();
System.out.println(max); // 400
2. With a loop
Another way is to use a plain for
loop:
int[] array = new int[] { 400, 55, 3, 90 };
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
System.out.println(min); // 400