Pages

December 25, 2017

#Java8 : Looping a Map using forEach and Lambda expression..

1). POJO class of Employee.

public class Employee {   
    private String name;
    private int age;

   
    public Employee(String name, int age)
    {
        this.name=name;
        this.age=age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
   
    @Override
    public String toString() {
        return "name:"+this.name+", age:"+this.age;
    }   
}

2).
import java.util.HashMap;
import java.util.Map;

public class UsingForEach {
    /**
     * This method will create Map of employees
     * @return employees
     */
    private static Map < Integer, Employee >  getEmployeeList() {
        Map < Integer, Employee >  employees = new HashMap < Integer, Employee > ();
        employees.put(1,new Employee("Andreas Ehmich", 33));
        employees.put(2,new Employee("Michael Andrew", 54));
        employees.put(3,new Employee("Chamuel Matthew", 45));
        employees.put(4,new Employee("Tiger Khan", 27));
        employees.put(5,new Employee("Himaanshu Shuklaa", 32));
        return employees;
    }
   
    public static void main(String[] args) {
        Map < Integer, Employee >  employees=getEmployeeList();

        System.out.println("Looping a Map in normal way..");
        for(Map.Entry < Integer, Employee >  employee: employees.entrySet())
        {
            System.out.println("Employee ID:"+employee.getKey()+", employee details are "+employee.getValue());
        }
       
        System.out.println("Looping a Map in using forEach and Lamda expression..");
        employees.forEach((k, v)- > System.out.println("Employee ID:"+k+", employee details are "+v));
    }
}

Also Check : Java 8 Blogs

No comments:

Post a Comment