[英]Updating a List of Object from another list of object using java stream
我有一個對象 A 的列表
A{
name
age
dob
}
和對象 B 的列表
B{
name
dob
}
.
我總是得到 A.dob 為空的 A 列表。 和 B 的列表,其中 B.dob 具有價值。 我需要通過 A 列表和 B 列表循環查找使用每個 A 和 B 對象中的名稱字段的公共對象,並使用 B.dob 更新 A.dob
這可以使用流來完成嗎?
我建議在 forEach 循環中修改 A 對象的列表:
// define: List<A> aList =
// define: List<B> bList =
aList.forEach(aListElement -> {
// find the first B object with matching name:
Optional<B> matchingBElem = bList.stream()
.filter(bElem -> Objects.equals(aListElement.getName(), bElem.getName()))
.findFirst();
// and use it to set the dob value in this A list element:
if (matchingBElem.isPresent()) {
aListElement.setDob(matchingBElem.get().getDob());
}
}
);
您不應使用 Stream API 來更改對象的狀態。
如果您仍然想修改它,則可以迭代A
列表中的每個元素,如果 dob 為空,則過濾,根據B
列表中的相應名稱查找 dob。
List<A> aList = new ArrayList<>();
List<B> bList = new ArrayList<>();
aList.stream()
.filter( a -> a.dob == null)
.forEach( a -> {
Predicate<B> nameFilter = b -> b.name.equals(a.name);
a.dob = findDob(nameFilter, bList);
});
static String findDob(Predicate<B> nameFilter, List<B> bList) {
B b = bList.stream()
.filter(nameFilter)
.findFirst()
.orElse(new B());
return b.dob;
}
替代有效的解決方案:考慮到每個對象 B 都有一個唯一的名稱,您可以使用該映射准備查找和查找年齡,這樣您就不需要為aList
每次迭代迭代bList
List<A> aList = new ArrayList<>();
List<B> bList = new ArrayList<>();
Map<String, String> nameDobLookup = bList.stream()
.collect(Collectors.toMap(b -> b.name, b -> b.dob));
aList.stream()
.filter(a -> a.dob == null)
.forEach(a -> a.dob = nameDobLookup.get(a.name));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.