What is the best way to find the max of an array in Java?
I know it’s simple to write a function that finds the maximum value in an array of primitives, like this:
private static int maxValue(char[] chars) {
int max = chars[0];
for (int ktr = 0; ktr < chars.length; ktr++) {
if (chars[ktr] > max) {
max = chars[ktr];
}
}
return max;
}
But isn’t there a built-in method for this? Instead of writing a custom function, is there a more efficient or standard way to find the max of an array in Java?
1 Like
Hey, if you’re using Java 8 or later, you don’t need to manually loop through the array to find the max value. You can use Arrays.stream()
, which makes it super simple!
import java.util.Arrays;
public class MaxValueExample {
public static void main(String[] args) {
int[] numbers = {5, 12, 8, 21, 14};
int max = Arrays.stream(numbers).max().getAsInt();
System.out.println("Max value: " + max);
}
}
Why use this? It’s clean, readable, and uses built-in Java features to get the job done efficiently. So, for finding the max of array java, this is a go-to if you’re on Java 8 or higher.
Good point, Akansha! But if you’re dealing with a List
instead of an array, there’s an even more straightforward way using Collections.max()
.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MaxValueExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 12, 8, 21, 14);
int max = Collections.max(numbers);
System.out.println("Max value: " + max);
}
}
Why use this? If you’re working with Lists
instead of arrays, this is the best approach for finding the max of array java when dealing with collections.
Exactly, Joe! But, if you’re using an older version of Java or just prefer a manual approach, a traditional loop can still work perfectly well.
public class MaxValueExample {
public static void main(String[] args) {
int[] numbers = {5, 12, 8, 21, 14};
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
System.out.println("Max value: " + max);
}
}
Why use this? It’s straightforward and works in all versions of Java, even those before Java 8. So if you’re dealing with the max of array java in an older Java environment, this classic loop will still serve you well.