There are many ways to find the max and min values in a Java array. We will explore the following:
Finding the maximum and minimum values in a Java array using the sort() method from Arrays class
We can use the sort() method from the Arrays class to sort the array first, and we can say that its first element would be the minimum value, and the last element would be the maximum value.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] array = new int[]{17, 28, 9, 4, 22, 7, 1, 3, 19, 42, 58, 47}; // first sort the array Arrays.sort(array); //print the minimum value (first number in an array) System.out.println("Minimum value: " + array[0]); //print the maximum value (last number in an array) System.out.println("Maximum value: " + array[array.length - 1]); } }
Output: Minimum value: 1 Maximum value: 58
Finding the maximum and minimum values in a Java array using the Java 8 Streams
We can use the min() and max() Stream operations that accept the Comparator to find the max and min values in a Java array.
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] array = new int[]{17, 28, 9, 4, 22, 7, 1, 3, 19, 42, 58, 47}; System.out.println("Minimum value: " + Arrays.stream(array).boxed().min(Integer::compare).get()); System.out.println("Maximum value: " + Arrays.stream(array).boxed().max(Integer::compare).get()); } }
Output: Minimum value: 1 Maximum value: 58
Here, we called the get() method because both max() and min() methods return the Optional.
Finding the max and min values in a array using iteration
We can find the max and min values using the for loop like in the following example:
public class Test { public static void main(String[] args) { int[] array = new int[]{17, 28, 9, 4, 22, 7, 1, 3, 19, 42, 58, 47}; System.out.println("Minimum value: " + getMin(array)); System.out.println("Maximum value: " + getMax(array)); } private static int getMax(int[] numbers) { int maximum = -1; for (Integer number : numbers) { if (number > maximum) { maximum = number; } } return maximum; } private static int getMin(int[] numbers) { int minimum = Integer.MAX_VALUE; for (Integer number : numbers) { if (number < minimum) { minimum = number; } } return minimum; } }
Output: Minimum value: 1 Maximum value: 58
Happy coding!