educative.io

How to convert this enhanced loop to simple for loop in java

for(Employee emp : list) {

        if(emp.age > 50) {

            System.out.println(emp.name);

        }

    }

Course: https://www.educative.io/collection/6650775272947712/6368023997317120
Lesson: https://www.educative.io/collection/page/6650775272947712/6368023997317120/6514798162870272

Hi @Ritu_Gupta !!
To convert the enhanced for loop to a simple for loop in Java, you can use the following code:

for (int i = 0; i < list.size(); i++) {
    Employee emp = list.get(i);
    
    if (emp.age > 50) {
        System.out.println(emp.name);
    }
}

In the above code, we use a traditional for loop with an index variable i that starts from 0 and iterates until i is less than the size of the list (list.size()). We retrieve each Employee object from the list using the get() method and assign it to the variable emp.

Then, we can apply the condition emp.age > 50 to check if the employee’s age is greater than 50, and if it is, we print the employee’s name using System.out.println(emp.name).

By using this approach, you can achieve the same functionality as the enhanced for loop but with a traditional for loop.
I hope it helps. Happy Learning :blush: