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.
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.
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> .
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With