Lambda表达式将一个列表中的对象添加到另一种类型的列表

7

有一个 List<MyObject>,需要使用其中的对象创建另一个列表 List<OtherObject> 中的对象:

下面是我的做法:

List<MyObject> myList = returnsList();
List<OtherObj> emptyList = new ArrayList();

for(MyObject obj: myList) {   
    OtherObj oo = new OtherObj();
    oo.setUserName(obj.getName());
    oo.setUserAge(obj.getMaxAge());   
    emptyList.add(oo);  
}

我正在寻找一个Lambda表达式来执行完全相同的操作。
3个回答

10

如果您定义了构造函数OtherObj(String name, Integer maxAge),则可以使用Java8样式进行操作:

myList.stream()
    .map(obj -> new OtherObj(obj.getName(), obj.getMaxAge()))
    .collect(Collectors.toList());

这将把列表 myList 中的所有对象映射为 OtherObj 并收集到包含这些对象的新 List 中。


谢谢再见。但是如果我没有修改OtherObj的权限怎么办? - Débora
4
您可以像这样操作:.map(obj -> { final OtherObj obj2 = new OtherObj(); // 创建一个新的OtherObj对象 obj2.setName(obj.getName()); // 将原始对象的名称属性赋值给新对象 obj2.setMaxAge(obj.getMaxAge()); // 将原始对象的最大年龄属性赋值给新对象 return po; // 返回新对象 }).collect(Collectors.toList()); - ByeBye

1
你可以在OtherObject中创建一个构造函数,使用MyObject的属性。
public OtherObject(MyObject myObj) {
   this.username = myObj.getName();
   this.userAge = myObj.getAge();
}

您可以按照以下步骤从MyObject创建OtherObject

myObjs.stream().map(OtherObject::new).collect(Collectors.toList());

0

我看到这是一篇相当老的帖子。然而,我根据之前的答案提出了我的看法。我的回答中唯一的修改是使用 .collect(ArrayList::new, ArrayList::add,ArrayList:addAll)

示例代码:

List<OtherObj> emptyList = myList.stream()
.map(obj -> {   
OtherObj oo = new OtherObj();
oo.setUserName(obj.getName());
oo.setUserAge(obj.getMaxAge());   
return oo; })
.collect(ArrayList::new, ArrayList::add,ArrayList::addAll);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接