I want to generate a list of objects from existing list of objects using some properties present in existing list.
For example,
I have List<Car> cars
public Class Car {
Integer carId;
String carName;
Integer engineId;
String engineName;
Double engineCapacity;
}
Class Engine {
Integer engineId;
String engineName;
Double engineCapacity;
}
I want to create List<Engine> engines from existing list of cars such that for each Car object there will be one engine object in the list with all the attributes populated using cars list. Is this possible using Java 8 stream/Lambda.
Actually it should be sufficient to map the list of cars to a list of their engines as they are already populated i suppose.
List<Engine> = cars.stream().map(Car::getEngine).collect(Collectors.toList());
You should be aware, that these Engines are references to the engines in the car objects. So changing their attributes through the cars should also reflect in the list of engines.
If you want to have different objects of engines (but holding the same values as the engines in the cars) you should try the answer of kocko.
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