1 minute read Published:

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());