Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the new for loop in Java be used with two variables?

Tags:

java

We can use the old for loop (for(i = 0, j = 0; i<30; i++,j++)) with two variables Can we use the for-each loop (or the enhanced for loop) in java (for(Item item : items) with two variables? What's the syntax for that?

like image 598
dogfish Avatar asked Aug 04 '13 17:08

dogfish


2 Answers

The following should have the same (performance) effect that you are trying to achieve:

List<Item> aItems = new List<Item>();
List<Item> bItems = new List<Item>();
...
Iterator aIterator = aItems.iterator();
Iterator bIterator = bItems.iterator();
while (aIterator.hasNext() && bIterator.hasNext()) {
    Item aItem = aIterator.next();
    Item bItem = bIterator.next();
}
like image 115
ajuser Avatar answered Oct 17 '22 09:10

ajuser


Unfortunately, Java supports only a rudimentary foreach loop, called the enhanced for loop. Other languages, especially FP ones like Scala, support a construct known as list comprehension (Scala calls it for comprehension) which allows nested iterations, as well as filtering of elements along the way.

like image 28
Marko Topolnik Avatar answered Oct 17 '22 08:10

Marko Topolnik