Apr 4, 2014

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 from which the other interfaces like Collection, List, etc has been annotated with @FunctionalInterface.

As shown in the diagram, the  Iterable also has a default  method  forEach(Consumer action)  implemented to loop through the collection.

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;
 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");});



The output will be

[Person [firstName=John, surname=Smith], Person [firstName=Peter, surname=Smith]]

More on Java 8 functional interfaces and Lambda expressions

Labels: ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home