Java Foreach Index: Get Loop Position

In Java, you can use a regular for loop to access the index of elements, for example:

String[] arr = {"a", "b", "c", "d"};

for (int i = 0; i < arr.length; i++) {
    System.out.println("Index: " + i + ", Element: " + arr[i]);
}

If you want to use a foreach loop to get the index, you can use a variable to keep track of the index, for example:

String[] arr = {"a", "b", "c", "d"};
int index = 0;

for (String element : arr) {
    System.out.println("Index: " + index + ", Element: " + element);
    index++;
}

In Java 8, the range method of IntStream was introduced for obtaining indexes. For example:

String[] arr = {"a", "b", "c", "d"};

IntStream.range(0, arr.length)
         .forEach(i -> {
             System.out.println("Index: " + i + ", Element: " + arr[i]);
         });
bannerAds