How to loop through an array with the index
Short answer
An ordinary for loop gives you both the index and the value:
void main() {
String[] fruits = {"apple", "banana", "cherry"};
for (int i = 0; i < fruits.length; i++) {
IO.println(i + ": " + fruits[i]);
}
}Output:
0: apple
1: banana
2: cherryValues only
If you do not need the index, for-each is shorter and keeps you from getting the bounds wrong:
void main() {
String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
IO.println(fruit);
}
}Output:
apple
banana
cherryWith a stream
IntStream.range() walks the indexes in stream style:
void main() {
String[] fruits = {"apple", "banana", "cherry"};
IntStream.range(0, fruits.length)
.filter(i -> i % 2 == 0)
.forEach(i -> IO.println(i + " " + fruits[i]));
}Output:
0 apple
2 cherryBackwards
To iterate backwards, start at length - 1:
void main() {
int[] numbers = {1, 2, 3};
for (int i = numbers.length - 1; i >= 0; i--) {
IO.print(numbers[i] + " ");
}
IO.println();
}Output:
3 2 1Common mistake
Using the condition i <= length. The last index of an array is length - 1:
void main() {
int[] numbers = {1, 2, 3};
for (int i = 0; i <= numbers.length; i++) {
IO.println(numbers[i]);
}
}Output:
1
2
3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3Functions used in this recipe
- IntStream.range() — Creates a stream of integers from a range.
- for — A loop with a counter, or iteration over every element of an array or collection (for-each).
- Iterable — The interface of everything that a for-each loop can iterate over.