Java Enhanced For Statement (Get an array or collection in a loop)

This is a sample of Java's Enhanced For Statement. Get the value of an array or collection in a loop.

Table of Contents

sample What is the Enhanced For statement?
  Get the value of an array / Get the value of a list
  Get the key and value of the map
Getting out of the loop(break)
Return to the top of the loop(continue)

What is the Enhanced For statement?

for( data type Variable1 : Variables in arrays and collections ){
    Process to be executed (using variable 1)
}
  • Accesses the values of an array or collection in order.
  • It is called an Enhanced For statement because it does not use a variable to count.

Get the value of an array

package test1;

public class Test1 {
	public static void main(String[] args) {
		int array[] = {1, 2, 3};

		for (int i: array){
		  System.out.println(i); //1 2 3
		}
 	}
}

Line 5 is an array.
Line 7 is an Enhanced For statement to get the value of the array.

Get the value of a list

package test1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test1 {
	public static void main(String[] args) {
		List<String> c = new ArrayList<>(Arrays.asList("one","two","three"));

		for (String a : c) {
			System.out.println(a); //one two three
		}
	}
}

Line 8 is a list.
Line 10 is an Enhanced for statement to get the value of the list.

Get the key and value of the map

package test1;
import java.util.HashMap;
import java.util.Map;

public class Test1 {
	public static void main(String[] args) {
		Map<String,String> color = new HashMap<>();
		color.put("a", "one");
		color.put("b", "two");
		color.put("c", "three");
		
		for (Map.Entry<String, String> c1 : color.entrySet()) {
			System.out.println(c1.getKey());// a b c
			System.out.println(c1.getValue());//one two three
		}
	}
 }

Line 7 is a map.
Line 12 is an Enhanced for statement.
Lines 13 and 14 get the keys and values of the map.

Getting out of the loop(break)

	List<String> c1 = new ArrayList<>(Arrays.asList("red","yellow","blue"));
		
	for (String a : c1) {
		if (a == "yellow"){
			break;
		}
		System.out.println(a); // red
	}

Line 5 breaks out of the loop of the Enhanced for statement with break.
Only the result "red" will be printed.

Return to the top of the loop(continue)

	List<String> c1 = new ArrayList<>(Arrays.asList("red","yellow","blue"));
	
	for (String a : c1) {
		if (a == "yellow"){
			continue;
		}
		System.out.println(a); // red blue
	}

Line 5 returns to the beginning of the extended for statement (line 3) with continue.
The results "red" and "blue" are output.

Related Articles

Java for文 処理を繰り返す(break/continue)
Java 配列の仕組みと使い方のサンプル
Java 配列からリスト・セットを作成(addAll/asList)

△上に戻る