Lambda expression to add objects from one list to another type of list

27,279

Solution 1

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.

Solution 2

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());
Share:
27,279
Débora
Author by

Débora

Updated on February 26, 2020

Comments

  • Débora
    Débora about 4 years

    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.