You can simply use the new Java 8 [`Stream`s](
[To see links please register here]
) but you have to work with `int`.
The [`stream`](
[To see links please register here]
) method of the utility class [`Arrays`](
[To see links please register here]
) gives you an [`IntStream`](
[To see links please register here]
) on which you can use the [`min`](
[To see links please register here]
) method. You can also do [`max`](
[To see links please register here]
), [`sum`](
[To see links please register here]
), [`average`](
[To see links please register here]
),...
The [`getAsInt`](
[To see links please register here]
) method is used to get the value from the [`OptionalInt`](
[To see links please register here]
)
import java.util.Arrays;
public class Test {
public static void main(String[] args){
int[] tab = {12, 1, 21, 8};
int min = Arrays.stream(tab).min().getAsInt();
int max = Arrays.stream(tab).max().getAsInt();
System.out.println("Min = " + min);
System.out.println("Max = " + max)
}
}
**==UPDATE==**
If execution time is important and you want to go through the data only once you can use the [`summaryStatistics()`](
[To see links please register here]
) method like this
import java.util.Arrays;
import java.util.IntSummaryStatistics;
public class SOTest {
public static void main(String[] args){
int[] tab = {12, 1, 21, 8};
IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics();
int min = stat.getMin();
int max = stat.getMax();
System.out.println("Min = " + min);
System.out.println("Max = " + max);
}
}
This approach can give better performance than classical loop because the [`summaryStatistics`](
[To see links please register here]
) method is a [reduction operation](
[To see links please register here]
) and it allows parallelization.