Prior to Java 8, iterating over a list of object was done using normal for loop or advanced for loop in case of Generics collection. In Java 8, forEach method of a List interface is used to iterate over the list of objects.
forEach method takes a single parameter that is actual object type of which the collection or list object is made of.
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 list using forEach method and prints the 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; } }
IterateList.java
package com.lambda; import java.util.ArrayList; import java.util.List; import com.pojo.Person; public class IterateList { public static void main(String args[]) { List<Person> persons = new ArrayList<>(); Person person = new Person(); person.setAge(20); persons.add(person); Person personOne = new Person(); personOne.setAge(25); persons.add(personOne); Person personTwo = new Person(); personTwo.setAge(32); persons.add(personTwo); Person personThree = new Person(); personThree.setAge(14); persons.add(personThree); persons.forEach(personObject -> { System.out.println("Person Name - " + personObject.getAge()); }); } }
No comments:
Post a Comment