lxdr lxdr - 1 year ago 59
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

of type

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

I would like to update the
attribute of each
in my
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++) {

How can I accomplish this same logic with Java Streams?

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

Answer Source

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())
            i -> myListOfCars.get(i).setEngine(myListOfEngines.get(i)

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