Débora
Débora

Reputation: 5952

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.

Upvotes: 7

Views: 33504

Answers (3)

kots_14
kots_14

Reputation: 141

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

Upvotes: 0

Akash Thakare
Akash Thakare

Reputation: 22972

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 OtherObjects from MyObjects,

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

Upvotes: 1

ByeBye
ByeBye

Reputation: 6946

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.

Upvotes: 10

Related Questions