Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 234
Débora Avatar asked Aug 19 '16 15:08

Débora


People also ask

Can lambda expressions contain data types?

The lambda expressions have a very simple, precise syntax and provide flexibility to specify the datatypes for the function parameters. Its return type is a parameter -> expression body to understand the syntax, we can divide it into three parts.

How do I convert a list from one type to another in C#?

The recommended approach to convert a list of one type to another type is using the List<T>. ConvertAll() method. It returns a list of the target type containing the converted elements from the current list. The following example demonstrates how to use the ConvertAll() method to convert List<int> to List<string> .

Which type of object is created in a lambda expression?

Core Java bootcamp program with Hands on practice Yes, any lambda expression is an object in Java. It is an instance of a functional interface. We have assigned a lambda expression to any variable and pass it like any other object.


2 Answers

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.

like image 65
ByeBye Avatar answered Nov 15 '22 04:11

ByeBye


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());
like image 33
akash Avatar answered Nov 15 '22 04:11

akash