Reputation: 367
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
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
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