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