JAVA - 如何有效地将 属性 从一个列表映射到另一个列表?

JAVA - How to map efficiently a property from a list to an other?

所以我有那两个对象

public class Setting {

@Id
private Long fooId;

@Transient
private String fooLabel

//GETTER and SETTER ommited
}

public class Foo {

@Id
private Long id;

@Column
private String fooLabelEn

@Column
private String fooLabelFr

public getLocalLabel(){}
}

我可以轻松获得所需的英文或其他语言的标签,我想将其添加到我的设置列表中。我无法修改 Foo table,也无法在设置中保存所有标签。

我试过类似的东西,但它不是很有效。

fooList = fooRepository.findAllById(settingIdList);
settingList.stream()
    .map(setting -> setting.setLabel(fooList.stream()
        .filter(foo -> foo.getId().equals(setting.getFooId())
        .findFirst()
        .get()
        .getLocalLabel)
    )
    .collect(Collectors.toList());

我想我忘记了什么,我觉得我没有朝着正确的方向前进。我只能保存设置的id,所以我必须做这样的事情。

有没有人有合适的解决方案?

感谢您的帮助。

只是为了帮助更好地解释@tevemadar 的建议,因为您已经能够从数据源中检索 fooList,您可以通过将结果转换为地图来更进一步,如下所示:

Map<Long, Foo> fooMap = fooRepository.findAllById(settingIdList).stream().collect(Collectors.toMap(Foo::getId, foo -> foo))

现在您可以执行以下操作:

settingList.stream()
    .peek(setting -> setting.setLabel(fooMap.get(setting.getFooId()).getLocalLabel()))
    .collect(Collectors.toList());

可以说这可能不是完全空安全的,假设您在 fooMap 中找不到 setting.getFooId()。您可以做的是:

settingList.stream()
    .peek(setting -> setting.setLabel(fooMap.getOrDefault(setting.getFooId(), new Foo(-1)).getLocalLabel()))
    .collect(Collectors.toList());

其中 new Foo(-1) 创建了 foo 的原始实例,其中 localLabel 设置为 -1。现在完全取决于您的实施,您可能不想要这个。