Functions example

Setup

class Person {

    private int personId;
    private String jobDescription;

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


    public int getPersonId() {
        return personId;
    }

    public String getJobDescription() {
        return jobDescription;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(Person.class)
                .add("personid", personId)
                .add("job description", jobDescription)
                .toString();
    }

}

class Job {

    private int personId;
    private String description;

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


    public int getPersonId() {
        return personId;
    }

    public String getDescription() {
        return description;
    }


    @Override
    public String toString() {
        return Objects.toStringHelper(Job.class)
                .add("personid", personId)
                .add("job description", description)
                .toString();
    }

}

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

Map from object to object

/**
 * Map a list of persons to jobs
 */
 @Test
public void map_obects_with_guava_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 = Lists.transform(persons, mapPersonToJob);

    logger.info(jobs);

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

Output

[
    Job{personid=1, job description=Husband},
    Job{personid=2, job description=Dad},
    Job{personid=3, job description=Software engineer},
    Job{personid=4, job description=Adjunct instructor},
    Job{personid=5, job description=Pepperoni hanger}
]