user2802764
user2802764

Reputation: 367

Merge two different object lists into one with a shared id field

I have two different objects list like those:

public class Person {
    private int id;
    private String name;
    private String surname;
}

public class Name {
    private int id;
    private String name;
}

My Person list doesn't have the field name filled. I need to merge it with the Name list matching the field id.

Question: How is the best way to do this with Java 8 streams?

Upvotes: 1

Views: 523

Answers (2)

Ali
Ali

Reputation: 117

First, using a Map is better for accessing the Name objects, so using streams here is a solution:

List<Person> personList = ...
List<Name> nameList = ...
Map<Integer,String> nameMap = nameList.stream()
.collect(Collectors.toMap(Name::getId,Name::getName));
personList.forEach(person -> person.setName(nameMap.getOrDefault(person.getId(), "")));

Upvotes: 2

Dani Mesejo
Dani Mesejo

Reputation: 61910

You can do it like this:

 Map<Integer, String> map = names.stream().collect(Collectors.toMap(o -> o.id, o -> o.name));
 for (Person person : persons) {
    person.name = map.getOrDefault(person.id, "");
 }

Assuming names is your list of Names and persons is your list of Person, also if the person id is not found the default name is the empty string.

Upvotes: 2

Related Questions