Get Index Of Element of Array Using Foreach Loop in Java

If given an Array with very large size, there use cases where you are required to get the index of an element of the Array using foreach loop in Java. You may want to see my post on Get Index Of Given Element Of Array Using for Loop in Java. Use the length property to determine the number of elements of the Array. The foreach loop is another loop that can be used to loop through an array to retrieve all the elements and their indexes or a single element and its index. Just like my post on for loop, the codes to retrieve of all elements, elements and their corresponding indexes will be added. The code to output the index of an element of an Array using foreach loop will also be part of this post.

Use foreach Loop to Loop Through An Array
Use the for-each  loop to loop through the elements in Arrays. The code below outputs all the elements of the states array.

 String[] states = {"Texas", "Maryland", "Idaho", "Ohio", "Florida", "Georgia"};
for (String state : states) {
  System.out.println(state);
}

The output of the above code.

Texas
Maryland
Idaho
Ohio
Florida
Georgia

Consider the code below that outputs both the elements and their indexes:

String[] states = {"Ohio", "Texas", "Idaho", "Kansas", "Florida", "Georgia"};
 int index = 0;
for (String state : states) {
  System.out.println(state + ": " + index);
  index++;
}

The output shows the elements of the array states and their corresponding indexes.

Ohio: 0
Texas: 1
Idaho: 2
Kansas: 3
Florida: 4
Georgia: 5

To get the index of an element of the Array using foreach loop in Java, use the code below

String[] states = {"Ohio", "Texas", "Idaho", "Kansas", "Florida", "Georgia"};
 int index = 0;
for (String state : states) {
  if(state == "Kansas") {
  System.out.println("The index of the state of " + state + " is " + index);
  index++; // this statement must be added here also
  }else {
 System.out.println(state + ": " + index);
 index++;
   }
  }

The output below depends on your use case. If you are only interested in the state of Kansas, remove all other lines.

Ohio: 0
Texas: 1
Idaho: 2
The index of the state of Kansas is 3
Florida: 4
Georgia: 5

Reference

W3Schools

Leave a Reply