lxdr lxdr - 4 months ago 10
Java Question

How to update Engine attributes of a List of type Car from a List of type Engine using Java Streams

I have a

List
of type
Car


public class Car {
private String make;
private String model;
private Engine engine;
//getters and setters below...
}


I would like to update the
Engine
attribute of each
Car
in my
List
from a List of Engines I have. With for-loops I would accomplish this by:

if (myListOfCars.size() == myListOfEngines.size()) {
for (int i = 0; i < myListOfCars.length(); i++) {
myListOfCars.get(i).setEngine(myListOfEngines.get(i));
}
}


How can I accomplish this same logic with Java Streams?

If you have suggestions for a better title please share them.

Answer

In my opinion the for loop is a little more readable, but this would do the job, as well.

if (myListOfCars.size() == myListOfEngines.size()) {
    IntStream.range(0, myListOfCars.size())
        .forEach(
            i -> myListOfCars.get(i).setEngine(myListOfEngines.get(i)
        )
    );
}

Note that I've replaced .length() with .size() if you copy it.