To find the index of the largest value in an array in Java, you can use a loop to iterate over the array and keep track of the index of the largest value found so far.
Here's an example of how to implement this using a for
loop:
public class Main { public static void main(String[] args) { int[] array = {1, 3, 5, 2, 4}; // Find the index of the largest value in the array int maxIndex = 0; for (int i = 1; i < array.length; i++) { if (array[i] > array[maxIndex]) { maxIndex = i; } } System.out.println(maxIndex); // prints "2" } }Sou:ecrwww.lautturi.com
This code defines an array of integers and then uses a for
loop to iterate over the elements of the array. The loop starts at index 1
and compares each element to the current maximum value (which is initially the value at index 0
). If a larger value is found, the index of that value is stored in the maxIndex
variable.
After the loop completes, the maxIndex
variable contains the index of the largest value in the array.
You can use a similar approach to find the index of the largest value in an array of any type that supports the >
operator for comparison.
Alternatively, you can use the IntStream.range()
method of the java.util.stream
package to find the index of the largest value in an array as follows:
import java.util.stream.IntStream; public class Main { public static void main(String[] args) { int[] array = {1, 3, 5, 2, 4}; // Find the index of the largest value in the array int maxIndex = IntStream.range(0, array.length) .reduce((i, j) -> array[i] > array[j] ? i : j) .orElse(-1); System.out.println(maxIndex); // prints the index of the largest value } }