[英]merge two different lists one is of wifi type other is of bluetooth type
[英]Merge two different object lists into one with a shared id field
我有兩個類似的對象列表:
public class Person {
private int id;
private String name;
private String surname;
}
public class Name {
private int id;
private String name;
}
我的Person
列表中沒有填寫字段名稱 。 我需要將其與匹配字段id的Name
列表合並。
問題 :如何用Java 8流實現此目的的最佳方法是什么?
您可以這樣做:
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, "");
}
假設names是您的Names
列表,persons是您的Person
列表,同樣,如果未找到person id
則默認name
為空字符串。
首先,使用Map
更好地訪問Name
對象,因此使用流是一種解決方案:
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(), "")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.