简体   繁体   中英

Foreach over certain part of a loop

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?

you can use

for(String eachIndex : Arrays.copyOfRange(arr, startingIndex, endingIndex)){
    //Do something
}

If you are willing to use Java8 then you can use

Arrays.stream(arr, startingIndex, endingIndex).forEach(eachIndex->{ 
        //Do Something
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM