Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: how many times is the collection expression evaluated in a "foreach"

if I do this in Java:

for(String s : myCollection.expensiveListGeneration()) {       doSomething(); } 

is expensiveListGeneration() invoked just once at the beggining or in every cycle iteration?

Is it implementation dependent?

like image 251
flybywire Avatar asked Aug 31 '09 10:08

flybywire


People also ask

How does forEach work in Java?

The forEach method was introduced in Java 8. It provides programmers a new, concise way of iterating over a collection. The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Is forEach faster Java?

As it turned out, FOREACH is faster on arrays than FOR with length chasing. On list structures, FOREACH is slower than FOR. The code looks better when using FOREACH, and modern processors allow using it. However, if you need to highly optimize your codebase, it is better to use FOR.

Does forEach preserve order?

Yes. The foreach loop will iterate through the list in the order provided by the iterator() method.

What is foreach loop in Java?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.


2 Answers

because it is equivalent to using an iterator, it is equivalent to calling the collections' . iterator() method, and it is called once.

like image 153
Chii Avatar answered Sep 30 '22 07:09

Chii


It's invoked once, and not implementation dependant. The for-each loop is based on the Iterable interface. All it does is call the collection's iterator() method once at the beginning, and then works with that iterator.

like image 20
Michael Borgwardt Avatar answered Sep 30 '22 06:09

Michael Borgwardt