How to iterate a Map of objects using forEach and Lambda in Java 8 - Java @ Desk

Friday, November 10, 2017

How to iterate a Map of objects using forEach and Lambda in Java 8

How to iterate a Map of objects using forEach and Lambda in Java 8

Prior to Java 8, iterating over a map of object was done using normal Map.Entry interface. In Java 8, forEach method of a Map interface is used to iterate over the map of objects.

forEach method takes 2 parameters as key and value.

Below is the example of the same. Here is a Person class with name, age & address property. The main program creates 3 objects of Person class and iterate over the map using forEach method and prints the key and age of each person.

Person.java
package com.pojo;

public class Person {

 private String id;

 private String name;

 private String address;

 private int age;

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }
}


IterateMap.java
package com.lambda;

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

import com.pojo.Person;

public class IterateMap {

 public static void main(String args[]) {

  Map<String, Person> personMap = new HashMap<>();

  Person person = new Person();
  person.setAge(20);
  personMap.put("FirstPerson", person);

  Person personOne = new Person();
  personOne.setAge(25);
  personMap.put("SecondPerson", personOne);

  Person personTwo = new Person();
  personTwo.setAge(32);
  personMap.put("ThirdPerson", personTwo);

  Person personThree = new Person();
  personThree.setAge(14);
  personMap.put("FourthPerson", personThree);

  personMap.forEach((key, personValue) -> {
   System.out.println("Key : " + key + ", Person Age : " + personValue.getAge());
  });
 }
}








No comments:

Post a Comment