Quick Index
Syntax


The syntax of the enhanced for-loop is:

for (list_element_type loop_var: list) {
	code statement(s)
 

Basic Samples


The following samples demo this nice simple syntax for iterating over list elements.


public void iterationSample()
{
	List<String> colors = new ArrayList<String>(Arrays.asList("Yellow", "Cyan", "Magenta", "Green"));
	//Print the colors (one color per line) by iterating over the list elements (i.e. the colors)
	for (String eachColor: colors)
	{
		println(eachColor);
	}
}

public void print()
{
	//Print all countries in vertical list
	for (Country eachCountry: this.getCountries())
		println(eachCountry);
}

public Country countryNamed(String countryName)
{
	//Return the matching country (or null if none found)
	for (Country eachCountry: this.getCountries())
		if (eachCountry.getName().equalsIgnoreCase(countryName))
			return eachCountry;
	//None found, so return null (meaning nothing)
	return null;
}


Runnable Examples




References