Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of objects from List of Object of other class in Java

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.

like image 439
vaibhavvc1092 Avatar asked Jan 31 '26 13:01

vaibhavvc1092


1 Answers

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.

like image 109
Aron_dc Avatar answered Feb 03 '26 04:02

Aron_dc