使用java流从另一个对象列表更新对象列表

使用java流从另一个对象列表更新对象列表,java,collections,java-stream,Java,Collections,Java Stream,我有一个对象列表 A{ name age dob } 和对象B的列表 B{ name dob } 我总是得到A的列表,其中A.dob为空。以及B的列表,其中B.dob具有值。 我需要循环遍历A列表和B列表,使用每个A和B对象中的name字段查找公共对象,并使用B.dob更新A.dob 这可以使用streams实现吗?我建议修改forEach循环中的对象列表: // define: List<A> aList = // define: List<B> bList =

我有一个对象列表

A{
name
age
dob
}
和对象B的列表

B{
name
dob
}

我总是得到A的列表,其中A.dob为空。以及B的列表,其中B.dob具有值。 我需要循环遍历A列表和B列表,使用每个A和B对象中的name字段查找公共对象,并使用B.dob更新A.dob


这可以使用streams实现吗?

我建议修改forEach循环中的对象列表:

// 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());
            }

        }
);
//定义:列表列表列表=
//定义:列表bList=
aList.forEach(aListElement->{
//查找具有匹配名称的第一个B对象:
可选的matchingBElem=bList.stream()
.filter(bElem->Objects.equals(aListElement.getName(),bElem.getName()))
.findFirst();
//并使用它设置该列表元素中的dob值:
if(matchingBElem.isPresent()){
setDob(matchingBElem.get().getDob());
}
}
);

您不应该使用流API来更改对象的状态

如果你还想修改它, 您可以迭代
A
列表中的每个元素,如果dob为null,则过滤,根据
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;
}

我认为这违背了函数式编程的原则:流不是为了改变现有的集合,而是为了创建一个新的集合。这对我也很有用,非常感谢。现在我要看的是每一场比赛的表现
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));