Java 将对象从一个列表添加到另一种类型的列表的 Lambda 表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39042897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lambda expression to add objects from one list to another type of list
提问by Débora
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<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
表达式来做完全相同的事情。
采纳答案by ByeBye
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
包含这些对象的新对象。
回答by CoderCroc
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,
您可以执行以下操作以OtherObject
从MyObject
s创建s,
myObjs.stream().map(OtherObject::new).collect(Collectors.toList());
回答by kots_14
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);