When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes.
In normal for loop, we write three statements :
for( statement1; statement 2; statement3 )
{
//code to be executed
}
Statement 1 is executed before the execution of code, Statement 2 states the condition to be satisfied to execute the code and Statement 3 gets executed after the execution of the code block.
But if we look into the Generic For loop or for-each loop,
The generic for loop consists of three parameters :
- Iterator function: It gets called when the next value is needed. It receives both the invariant state and control variable as parameters. Returns nil signals for termination.
- Invariant state: This doesn't change during the iteration. It is basically the subject of the iteration such as String, table or user data.
- Control variable: It represents the initial value of the iteration.
Syntax
for( ObjectType variable : iterable/array/collections ){
// code using name variable
}
Equivalent to
for( int i=0 ; i< list.size() ; i++) {
ObjectType variable = list.get(i);
// statements using variable
}
Example:
Java
// Java program to illustrate Generic for loop
import java.io.*;
class GenericsForLoopExample {
public static void main(String[] args)
{
// create an array
int arr[] = { 120, 100, 34, 50, 75 };
// get the sum of array elements
int s = sum(arr);
// print the sum
System.out.println(s);
}
// returns the sum of array elements
public static int sum(int arr[])
{
// initialize the sum variable
int sum = 0;
// generic for loop where var stores the integer
// value stored at every index of array
for (int var : arr) {
sum += var;
}
return sum;
}
}
Example: Showing that
Java
// Java program to demonstrate that Generic
// for loop can be used in iterating
// Collections like HashMap
import java.io.*;
import java.util.*;
class EnhancedForLoopExample {
public static void main(String[] args)
{
// create a empty hashmap
HashMap<String, String> map = new HashMap<>();
// enter name/url pair
map.put("GFG", "geeksforgeeks.org");
map.put("Github", "www.github.com");
map.put("Practice", "practice.geeksforgeeks.org");
map.put("Quiz", "www.geeksforgeeks.org");
// using keySet() for storing
// all the keys in a Set
Set<String> key = map.keySet();
// Generic for loop for iterating all over the
// keySet
for (String k : key) {
System.out.println("key :" + k);
}
// Generic for loop for iterating all over the
// values
for (String url : map.values()) {
System.out.println("value :" + url);
}
}
}
Outputkey :Quiz
key :Github
key :Practice
key :GFG
value :www.geeksforgeeks.org
value :www.github.com
value :practice.geeksforgeeks.org
value :geeksforgeeks.org
Limitations of Generic For loop or for-each loop:
1. Not appropriate when we want to modify the list.
for( Integer var : arr)
{
// only changes the var value and not the value of the data stored inside the arr
var = var + 100;
}
2. We cannot keep track of the index.
for( Integer var : arr){
if(var == target)
{
// don't know the index of var to be compared with variable target
return **;
}
}
4. Iterates a single step in forward direction only.
// This cannot be converted to Generic for loop
for( int i = n-1 ; i >= 0 ; i-- ) {
// code
}
4. Cannot process two decision-making statements at once.
// This loop cannot be converted to Generic for loop
for( int i = 0; i < arr.length; i++ ) {
if( arr[i]==num )
return **;
}
Similar Reads
Generics in Java Generics means parameterized types. The idea is to allow a type (like Integer, String, etc., or user-defined types) to be a parameter to methods, classes, and interfaces. Generics in Java allow us to create classes, interfaces, and methods where the type of the data is specified as a parameter. If w
10 min read
Generic Set In Java The Set interface is present in java.util package. It is basically a collection of objects with no duplicate objects that means there can be no two objects in a Set e1 and e2 such that e1.equals(e2) and at most one null element. It is an interface that models the mathematical set. This interface inh
3 min read
Generic Class in Java Java Generics was introduced to deal with type-safe objects. It makes the code stable.Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types. Generics also provide compile-time type safety which allows programmers to c
4 min read
For-Each Loop in Java The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required.Example: Using a for-each lo
8 min read
Java For Loop Java for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections.Now let's go through a simple Java for lo
4 min read