JDK-6524774 : Nested for loops in Java
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2007-02-14
  • Updated: 2010-04-04
  • Resolved: 2007-02-14
Related Reports
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
It would be very convenient to be able to have multiple nested foreach loops into one foreach loop by adding as many ":" as  required.

JUSTIFICATION :
It's necessary to avoid wasting code space and the code will be very much like reading a sentence.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
this would require enhancing the current foreach loop in the following manner:

for(City city : Array<Country> countries : Array<Continent> continents : Array<planet> planets) {
    System.out.println("Here's a list of all the cities in the solar system: " + city.getName());
}

CUSTOMER SUBMITTED WORKAROUND :
use multiple for each loops; for example:

for(Planet planet : planets) {
   for(Continent continent : planet) {
      for(Country country : continent) {
        for(City city : country) {

    System.out.println("Here's a list of all the cities in the solar system: " + city.getName());

}

Comments
EVALUATION This request is reminiscent of 6402294, which proposed looping over multiple collections in parallel. Both save a minor amount of typing but impose a large burden on the programmer to construct the semantics of the loop in his head; in this case, to remember the order in which the collections are iterated. There's also a semantic gap in that 'city' comes not from the array of countries, but from each element of that array, yet those elements aren't explicit. Plus, the planet, continent and country loop variables which are available with explicit nested loops are not available within the loop body of the proposed construct; this rather restricts its usefulness. So while the construct might be convenient in some places, it's not appropriate as a general-purpose addition to the language.
14-02-2007