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) -> {
    return specificPerson;

Use this in a list:

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

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

Leave a Reply

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

You are commenting using your 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