Java 8 Internal Iteration: External vs. Internal Iteration

By Arvind Rai, April 27, 2014
Java 8 has introduced internal iteration. forEach can iterate the collection internally. Before java 8, there was no such way to iterate list internally. To iterate the collection we need to use for loop or while loop. Using forEach, now iteration is possible in one line. To understand internal and external iteration, follow the below example.

External Iteration

Suppose we have a list of employee and we need to update the salary of each and every employee multiplied by two. As old fashioned, we will do as below.
ExternalIterationDemo.java
package com.concretepage.util.stream;
import java.util.List;
public class ExternalIterationDemo {
    public static void main(String[] args) {
        List<Employee> list = Employee.getEmpList();
        for(Employee e : list){
            e.setSal(e.getSal()*2);
        }
    }
} 

Internal Iteration

Now the same task we will do in new fashion using forEach that will iterate collection internally. Find the code below.
InternalIterationDemo.java
package com.concretepage.util.stream;
import java.util.List;
public class InternalIterationDemo {
    public static void main(String[] args) {
        List<Employee> list = Employee.getEmpList();
        System.out.println("Salary before update");
        list.forEach(e->System.out.print(e.getSal()+"  "));
        list.forEach(e->e.setSal(e.getSal()*2));
        System.out.println("\nSalary after update");
        list.forEach(e->System.out.print(e.getSal()+"  "));
    }
} 
Output will be
Salary before update
2000  3000  4000  5000  
Salary after update
4000  6000  8000  10000
The Employee class we have used is given below.
Employee.java
package com.concretepage.util.stream;
import java.util.ArrayList;
import java.util.List;
public class Employee {
 public int id;
 public String name;
 private int sal;
 public Employee(int id,String name,int sal  ){
     this.id = id;
     this.name = name;
     this.sal = sal;
 }
 public void setSal(int sal) {
     this.sal = sal;
 }
 public int getSal() {
     return sal;
 }
  public static List<Employee> getEmpList(){
     List<Employee> list = new ArrayList<>();
     list.add(new Employee(1, "A", 2000));
     list.add(new Employee(2, "B", 3000));
     list.add(new Employee(3, "C", 4000));
     list.add(new Employee(4, "D", 5000));
     return list;
 }
} 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us