Lambda Function Apply Example

Java 8 introduced package java.util.function which contains very useful Function interface, it transform T to a U. Means when you implements this interface, It takes two parameter where first one is the type of the input to the function and second one is the type of the result of the function. It has only one method called apply which takes t as the function argument and return function result. In this example you will see how to use Java 8 Function interface:

  • LambdaFunctionImplementsExample.java:
package com.javahonk;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Java Honk
 *
 */
public class LambdaFunctionImplementsExample implements Function<List<Person>, List<Person>>{

	public static void main(String[] args) {
		
		LambdaFunctionImplementsExample lambdaFunctionImplementsExample = new LambdaFunctionImplementsExample();
		
		//Create list of Persons
		List<Person> persons = new ArrayList<Person>();
		
		persons.add(new Person("Java", "Honk", 25));
		persons.add(new Person("Java1", "Honk2", 35));
		persons.add(new Person("Java2", "Honk3", 45));
		
		//Pass person list to apply method which will return filtered list based on age
		List<Person> filteredList = lambdaFunctionImplementsExample.apply(persons);
		
		filteredList.forEach(System.out::println);

	}

	/* (non-Javadoc)
	 * @see java.util.function.Function#apply(java.lang.Object)
	 * Takes List of person and return filtered list based on age
	 */
	@Override
	public List<Person> apply(List<Person> persons) {
		
		List<Person> filteredListByAge = persons.stream().filter(person -> person.getAge() <= 35).collect(Collectors.toList());
		return filteredListByAge;
		
	}	

}


class Person {
	
	private String firstName;
	private String lastName;
	private Integer age;
	
	public Person(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 Apply Example

  • For more information please visit Oracle documentation here

Leave a Reply

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