Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 enhanced for loop with index/range

Is it possible to specify an index/range in enhanced for loop in Java?

For e.g. I have a list: List<String> list;

And I want to run a for loop from index 1 instead of 0:

for(String s : list(start from index 1))

OR till index 5

for(String s : list(end at index 5))

I know I can use traditional for loop or keep a counter inside the enhanced for loop but I wanted to know is there something out of the box in Java or apache collections?

like image 749
tryingToLearn Avatar asked Nov 19 '19 06:11

tryingToLearn


People also ask

Can you get an index with a enhanced for loop?

4) You don't have access to array index in enhanced for loop, which means you cannot replace the element at giving the index, but for loop provide access to the index, hence allows you to replace any element in the array.

Can you use enhanced for loop on array?

Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values.

Is enhanced for loop faster Java?

For a low number of iterations (100-1000), the enhanced for loop seems to be much faster with and without JIT. On the contrary with a high number of iterations (100000000), the traditional loop is much faster.


1 Answers

I would use subList in this case:

for(String s : list.subList(1, list.size()))

and

for(String s : list.subList(0, 6))
like image 181
ernest_k Avatar answered Oct 03 '22 06:10

ernest_k