Java 8 function example

Closely resembling the guava function, the java.util.function.Function<T,R> interface contains the method R apply(T t) when applied determines an output value based on an input value. A common usecase is when converting a list to map or when you want to convert or transform from one object to another. Since this is a functional interface it can be used as the assignment target for a lambda expression or method reference.

In the example below, we will map between a Person object and a Job object.

Setup

class Person {

    private int personId;
    private String jobDescription;

    public Person(int personId, String jobDescription) {
        super();
        this.personId = personId;
        this.jobDescription = jobDescription;
    }

    //..
}

class Job {

    private int personId;
    private String description;

    public Job(int personId, String description) {
        super();
        this.personId = personId;
        this.description = description;
    }

    //..

}

Function<Person, Job> mapPersonToJob = new Function<Person, Job>() {
    public Job apply(Person person) {
        Job job = new Job(person.getPersonId(), person.getJobDescription());
        return job;
    }
};

Map a list of objects

The Stream.map will apply the given function to all the elements in the stream. In this case, for every person object in person list, it will call the mapPersonToJob returning a Job object. We will then call the Stream.collect to convert the stream to a list.

@Test
public void map_objects_with_java8_function() {

    List<Person> persons = Lists.newArrayList(new Person(1, "Husband"),
            new Person(2, "Dad"), new Person(3, "Software engineer"),
            new Person(4, "Adjunct instructor"), new Person(5,
                    "Pepperoni hanger"));

    List<Job> jobs = persons.stream().map(mapPersonToJob)
            .collect(Collectors.toList());

    logger.info(jobs);

    assertEquals(5, jobs.size());
}

Map object to object

The function.apply method will apply this function to a given arguement. In this case, the function.apply will convert the Person object to a Job object.

@Test
public void apply() {

    Person person = new Person(1, "Description");
    
    Job job = mapPersonToJob.apply(person);
    
    assertEquals("Description", job.getDescription());
}