【问题标题】:Updating a List of Object from another list of object using java stream使用java流从另一个对象列表更新对象列表
【发布时间】:2020-02-19 15:41:43
【问题描述】:

我有一个对象 A 的列表

A{
name
age
dob
}

和对象B的列表

B{
name
dob
}

.

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

这可以使用流来完成吗?

【问题讨论】:

  • 我认为这违背了函数式编程的原则:流不是为了改变现有集合,而是创建一个新集合。

标签: java collections java-stream


【解决方案1】:

您不应使用 Stream 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;
}

另一种有效的解决方案:考虑到每个对象 B 都有一个唯一的名称,您可以使用该映射准备查找和查找年龄,这样您就不需要为每次迭代迭代 bListaList

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));

【讨论】:

  • 这也对我有用,非常感谢。现在我必须看看每个人的表现
【解决方案2】:

我建议在 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());
            }

        }
);

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2016-11-18
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多