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

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.


No you can't. It is syntactic sugar for using Iterator. Refer here for a good answer on this issue.

You need to have an object that contains both variables.

It can be shown on a Map object for example.

for (Map.Entry<String,String> e: map.entrySet()) {
    // you can use e.getKey() and e.getValue() here
}

Tags:

Java