Combining Two Objects in Java 8

Say you have a simple POJO:

@Getter @Setter
public class Person {
    private Long id;
    private String name;
}

You extend that POJO for a specific use case:

@Getter @Setter
public class SpecificPerson extends Person {
    private String role;
}

If you have a list of both instances how do you combine them?

List<Person> people;
List<SpecificPerson> specificPeople;

If both list contain a similar subset of people were Person has part of the data and SpecificPerson has the other part of the data a way to combine the two would be through a BiFunction. (This, of course, is a assuming you have a common attribute, like Id).

public static BiFunction<Person, SpecificPersion, SpecificPerson> fromPersonToSpecific =(person, specificPerson) -> {
    specificPerson.setName(person.getName());
    return specificPerson;
}

Use this in a list:

final Map<Long, Person> mappedPeople = people
    .stream()
    .collect(Collectors.toMap(Person:getId, Function.identity()));

List<SpecificPerson> s = specificPeople
    .stream()
    .map(specific ->fromPersonToSpecific.apply(mappedPeople.get(specificPeople.getId()), specificPerson))
    .collect(Collectors.toList());

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s