Understanding Java 8 Lambda expressions with working examples -- part 2
Extends Understanding Java 8 Lambda expressions with working examples -- part 1
Example 3: It is very common to loop through a collection of objects and perform certain tasks like setting a variable, etc. The Iterable
As shown in the diagram, the Iterable
Step 1: Create a Person POJO object with fields, getters, and setters.
package com.java8.examples; public class Person { private String firstName; private String surname; public Person(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } @Override public String toString() { return "Person [firstName=" + firstName + ", surname=" + surname + "]"; } }
Step 2: Create a collection of Person objects, and forEach person, set the surname using the Lambda expression and anonymous method call. This is functional programming.
package com.java8.examples; import java.util.ArrayList; import java.util.List; public class PersonCollectionTest { public static void main(String[] args) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("John")); persons.add(new Person("Peter")); // Java 8: Lambda expression that sets surname for each person as "Smith" persons.forEach((p) -> {p.setSurname("Smith");}); System.out.println(persons); } }
The output will be
[Person [firstName=John, surname=Smith], Person [firstName=Peter, surname=Smith]]
More on Java 8 functional interfaces and Lambda expressions
- Understanding Java 8 Lambda expressions : function interfaces and Lambda expressions
- Understanding Java 8 Lambda expressions : to create new threads as now Runnable interface is functional
Labels: Java 8, Java Lambda expressions
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home