Java 8 single line forEach for looping through Collection

Java 8 introduced a new forEach method for Iterables ( such as List ) as well as for Map.
Lets see an example of looping through List and Map using forEach ( which uses Lambda Expression ).

Example : forEach + Lambda Expression = Loop through Collection

package com.codeforeach.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Java8ForEachDemo {
  public static void main(String[] args) {
    /*
     * Java 8 forEach - List Example
     */
    List<Employee> l = new ArrayList<Employee>();
    l.add(new Employee("Naveen", 1000));
    l.add(new Employee("Hari", 2000));
    l.add(new Employee("Raju", 9000));
    System.out.println("Looping result for List :");
    // using forEach + Lambda Expression
    l.forEach(t -> System.out.println("Employee Name : " + t.getName() + " , Salary : " + t.getSalary()));
   
    /*
     * Java 8 forEach - Map Example
     */
    Map<String, Integer> m = new HashMap<>();
    m.put("Naveen", 1000);
    m.put("Hari", 2000);
    m.put("Raju", 9000);
    System.out.println("\nLooping result for Map :");
    // using forEach + Lambda Expression
    m.forEach((i, j) -> System.out.println("Name : " + i + " , Salary : " + j)); }
}

Employee.java

package com.codeforeach.demo;
public class Employee {
  private String name;
  private int salary;
  public Employee(String name, int salary) {
    this.name = name;
    this.salary = salary;
  }
  public String getName() {
    return name;
  }
  public int getSalary() {
    return salary;
  }
}
Looping result for List :
Employee Name : Naveen , Salary : 1000
Employee Name : Hari , Salary : 2000
Employee Name : Raju , Salary : 9000

Looping result for Map :
Name : Hari , Salary : 2000
Name : Naveen , Salary : 1000
Name : Raju , Salary : 9000

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

www.000webhost.com