Lambda Function Parameter Example

Lambda Function Parameter Example

As previous examples you saw how to Lambda which is introduced with Java 8. In this example you will see how to pass Function as parameter and retrieve it value:

  • LambdaFunctionParameter.java:
package com.javahonk;

import java.util.function.Function;

public class LambdaFunctionParameter {

	public static void main(String[] args) {
		
		//Call method which take Function as parameter
		Integer personAge = getAge(e->e.getAge());
		System.out.println("Age: "+personAge);

	}
	
	
	/**
	 * Takes Function as parameter
	 * @param age
	 * @return Integer age 
	 */
	private static Integer getAge(Function<People, Integer> age){		
		
		People people = new People("Java", "Honk", 25);
		return age.apply(people);
	}

}

class People {
	
	private String firstName;
	private String lastName;
	private Integer age;
	
	public People(String firstName, String lastName, Integer age) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
 
	public String getFirstName() {
		return firstName;
	}
 
	public String getLastName() {
		return lastName;
	}
 
	public Integer getAge() {
		return age;
	}

	@Override
	public String toString() {
		return "Person [firstName=" + firstName + ", lastName=" + lastName
				+ ", age=" + age + "]";
	}
	
}
  • Output:

Lambda Function Parameter Example

  • For more details please visit Oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *