Reputation: 7120
Let's say I have the following String
array.
String[] arr = {"Index0", "Index1", "Index2", "Index3",..."Index n"};
I can iterate over the entire array using:
for (String eachElement : arr){
//Do something
}
But what if I wanted to do a foreach
over a certain part of the array.
I know that I can do something like this with a for loop:
int startingIndex = 1;
int endingIndex = 3;
for (int i = startingIndex; i < endingIndex; i++){
//Do something
}
Is there a way I could do something similar using foreach
loop?
Upvotes: 2
Views: 146
Reputation: 5741
If you are willing to use Java8 then you can use
Arrays.stream(arr, startingIndex, endingIndex).forEach(eachIndex->{
//Do Something
});
Upvotes: 4
Reputation: 60244
you can use
for(String eachIndex : Arrays.copyOfRange(arr, startingIndex, endingIndex)){
//Do something
}
Upvotes: 6