In Java, the for loop is a fundamental construct used for iterating through a list of objects. It allows a block of statements to be repeated a specified number of times. Similar to the while and do-while loops, the for loop, along with the for-each loop, provides a means to traverse collection objects. The for loop is a simple and effective way to execute a block of code repeatedly, iterating through a list using an index. It can traverse collection objects both forward and backward. This section will delve into the usage of for and for-each loops in Java.

for loop in java

The Java for loop is a fundamental looping structure, typically initiated with the keyword “for.” It comprises three essential sections: initialization, increment/decrement, and a conditional statement. During initialization, a variable is set to control the index’s increase or decrease. The condition is a boolean expression, determining whether the loop should continue (true) or terminate (false). As long as the condition evaluates to true, the code block within the for loop will be executed, and the index will be incremented or decremented after each iteration. If the condition is false, the loop concludes.

package com.test;

public class JavaTest {

	public static void main(String[] args) {
		int values[] = { 10, 20, 30, 40 };
		for (int i = 0; i < values.length; i++) {
			System.out.println(i + " : " + values[i]);
		}
	}

}

for-each loop in java

The for-each loop in Java is a variation of the traditional for loop that iterates over collection objects without explicitly using an index. It starts with the keyword “for” and introduces a local variable declaration for the data type of the collection elements. The collection to be iterated is separated from the local variable declaration by a colon. Unlike the traditional for loop, the for-each loop does not involve an explicit index, and neither the index nor the elements’ positions can be used to manipulate the collection or exit the loop.

package com.test;

public class JavaTest {

	public static void main(String[] args) {
		int values[] = { 10, 20, 30, 40 };
		for (Integer value : values) {
			System.out.println(value);
		}
	}

}

forEach() in Iterable Interface

In Java, the Iterable interface supports the forEach method, introduced from Java 8 onwards. The forEach method is defined in the Iterable interface, and it is available for all collection objects. This method facilitates the iteration over the elements of a collection using the Iterable interface. The provided Java example illustrates how to utilize the forEach method in the Iterable interface.

package com.test;

import java.util.ArrayList;

public class JavaTest {

	public static void main(String[] args) {
		ArrayList values = new ArrayList();
		values.add("10");
		values.add("20");
		values.add("30");
		values.add("40");
		values.forEach(value -> System.out.println(value));
	}

}

forEach() in Static Interface

The forEach method can be used with output streams. By passing the static reference of the println output stream as an argument to the forEach method, the elements are iterated and output to the println stream. The subsequent example demonstrates the usage of the forEach method with a static interface reference.

package com.test;

import java.util.ArrayList;

public class JavaTest {

	public static void main(String[] args) {
		ArrayList values = new ArrayList();
		values.add("10");
		values.add("20");
		values.add("30");
		values.add("40");
		values.forEach(System.out::println);
	}

}

forEach() using Consumer interface

The Consumer interface is employed in conjunction with the Java collection’s forEach() method. The accept method is a part of the Consumer interface. By overriding the accept method, the forEach() method can be utilized to iterate through collection objects. In each iteration, the Consumer interface facilitates the execution of a block of statements. The following example illustrates how to leverage the Consumer interface for iterating through the forEach() method.

package com.test;

import java.util.ArrayList;
import java.util.function.Consumer;

public class JavaTest {

	public static void main(String[] args) {
		ArrayList values = new ArrayList();
		values.add("10");
		values.add("20");
		values.add("30");
		values.add("40");
		values.forEach(new Consumer() {
            @Override
            public void accept(String value) {
                System.out.println(value);
            }
        });
	}

}

forEach() using Java Map

Java maps can utilize the forEach() method to iterate through the key-value pairs within the collection. In Java maps, values are stored in key-value pairs, where each value is identified by a unique key. The forEach method allows iteration through all key-value pairs in the Map objects. The following example illustrates how to iterate over a map using the forEach() method.

package com.test;

import java.util.HashMap;

public class JavaTest {

	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("10", "ten");
		map.put("20", "twenty");
		map.put("30", "thirty");
		map.put("40", "fourty");
		
		map.forEach((k, v) -> {
			System.out.println(k+" "+v);
		});
	}

}

Leave a Reply