简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM