简体   繁体   中英

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> .

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.

If you define constructor OtherObj(String name, Integer maxAge) you can do it this java8 style:

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.

You can create a constructor in OtherObject which uses MyObject attributes,

public OtherObject(MyObject myObj) {
   this.username = myObj.getName();
   this.userAge = myObj.getAge();
}

and you can do following to create OtherObject s from MyObject s,

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) .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM