[英]Lambda expression to add objects from one list to another type of list
There is a List<MyObject>
and it's objects are required to create object that will be added to another List with different elements : List<OtherObject>
. 有一个
List<MyObject>
,它的对象是创建将添加到具有不同元素的另一个List的对象所必需的: List<OtherObject>
。
This is how I am doing, 这就是我的表现,
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);
}
I'm looking for a lamdba
expression to do the exact same thing. 我正在寻找一个
lamdba
表达式来完成同样的事情。
If you define constructor OtherObj(String name, Integer maxAge)
you can do it this java8 style: 如果定义构造函数
OtherObj(String name, Integer maxAge)
,则可以使用java8样式:
myList.stream()
.map(obj -> new OtherObj(obj.getName(), obj.getMaxAge()))
.collect(Collectors.toList());
This will map all objects in list myList
to OtherObj
and collect it to new List
containing these objects. 这将在列表中的所有对象映射
myList
以OtherObj
并收集到新的List
包含这些对象。
You can create a constructor in OtherObject
which uses MyObject
attributes, 您可以在
OtherObject
中使用MyObject
属性创建构造函数,
public OtherObject(MyObject myObj) {
this.username = myObj.getName();
this.userAge = myObj.getAge();
}
and you can do following to create OtherObject
s from MyObject
s, 并且您可以执行以下操作来从
MyObject
创建OtherObject
,
myObjs.stream().map(OtherObject::new).collect(Collectors.toList());
I see that this is quite old post. 我看到这是相当古老的帖子。 However, this is my take on this based on the previous answers.
但是,这是基于之前的答案我对此的看法。 The only modification in my answer is usage of
.collect(ArrayList::new, ArrayList::add,ArrayList:addAll)
. 我的答案中唯一的修改是使用
.collect(ArrayList::new, ArrayList::add,ArrayList:addAll)
。
Sample code : 示例代码:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.