[英]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.