使用Lambda按ID合并列表

使用Lambda按ID合并列表,lambda,java-8,Lambda,Java 8,我想知道是否有人能帮我简化下面的代码 我基本上有两个列表,我主要想检查第二个列表中的项是否与第一个列表中的项ID匹配。如果匹配,我想用第二个列表的值更新第一个列表中的对象 postPatch.getSections().forEach(patched -> { originalSection.getSections().forEach(original -> { if (original.getId().equals(pat

我想知道是否有人能帮我简化下面的代码

我基本上有两个列表,我主要想检查第二个列表中的项是否与第一个列表中的项ID匹配。如果匹配,我想用第二个列表的值更新第一个列表中的对象

        postPatch.getSections().forEach(patched -> {

        originalSection.getSections().forEach(original -> {

            if (original.getId().equals(patched.getId())) {
                original.setContent(patched.getContent());
                original.setImagePosition(patched.getImagePosition());
                original.setTitle(patched.getTitle());
                original.setImageUrl(patched.getImageUrl());
            }
        });
    });

我觉得有一种更好的方式可以用Java8来表达这一点,但是我找不到我想要的东西。

我认为你做得对。我会做一个单独的方法来更新

假设这是要更新的POJO类

public class Image {
    private Integer id;
    private String content;
    private Cell position;
    private String title;
    private URL imageURL;

    // ...

    public void updateIfMatch(Image patch) {
        if (Objects.equals(id, patch.id)) {
            id = patch.id;
            content = patch.content;
            position = patch.position;
            title = patch.title;
            imageURL = patch.imageURL;
        }
    }
}
下面是更新列表的代码

getPostPatchedSections().forEach(a -> getOriginalSections().forEach(a::updateIfMatch));
替代解决方案
您还可以在流中进行id比较,而不是在图像类中进行比较。这个解决方案更像Java 8ish

public class Image {
    private Integer id;
    private String content;
    private Cell position;
    private String title;
    private URL imageURL;

    // ...

    public void updateFrom(Image patch) {
        id = patch.id;
        content = patch.content;
        position = patch.position;
        title = patch.title;
        imageURL = patch.imageURL;
    }
}
下面是更新列表的管道代码

    getPostPatchedSections()
            .filter(Objects::nonNull)
            .forEach(a -> getOriginalSections()
                    .filter(a::equals)
                    .forEach(a::updateFrom));

听起来你真的很想使用地图,这样你就可以通过id查找播放器了

// Map of id to player.
Map<Integer, Player> players = new HashMap<>();

players.putAll(originalMap);

players.putAll(patchMap);
//将id映射到播放器。
Map players=newhashmap();
players.putAll(originalMap);
玩家。putAll(补丁地图);

patchMap中的所有条目都将添加或替换播放器中的条目,并与
id
匹配这是一个
O(n)
操作,而不是
O(n^2)

谢谢,这更接近我想要的。