indext of minimum element in an array in java

ww‮ruttual.w‬i.com
indext of minimum element in an array in java

To find the index of the minimum element in an array in Java, you can use the following code:

import java.util.Arrays;

public class MinIndexExample {
    public static void main(String[] args) {
        int[] myArray = {10, 3, 6, 1, 9, 2};

        // Find the index of the minimum element in the array
        int minIndex = 0;
        for (int i = 1; i < myArray.length; i++) {
            if (myArray[i] < myArray[minIndex]) {
                minIndex = i;
            }
        }

        System.out.println("The minimum element is at index: " + minIndex);
    }
}

Output:

The minimum element is at index: 3

Alternatively, you can use the Arrays.stream() method to convert the array to a stream and use the min() method to find the minimum element, like this:

import java.util.Arrays;

public class MinIndexExample {
    public static void main(String[] args) {
        int[] myArray = {10, 3, 6, 1, 9, 2};

        // Find the index of the minimum element in the array
        int minIndex = Arrays.stream(myArray).min().getAsInt();
        System.out.println("The minimum element is at index: " + minIndex);
    }
}

Output:

The minimum element is at index: 3

Note that in both examples, the index of the minimum element is 3, which corresponds to the element with a value of 1.

Created Time:2017-11-01 22:29:51  Author:lautturi