jeudi 16 août 2018

Map a single object using Stream

Is this a good use case of java 8's Stream:

final Car carWithInterior = Stream.of(carWithEngine)
            .map(car -> installSeats.execute(car))
            .map(car -> installDashBoard.execute(car))
            .map(car -> installSunRoof.execute(car))
            .collect(car);

carWithEngine is a Car. Note that sometimes even if the car (w/ dashboard) is pass to the installSunroof, it will not do any since there's no hole in the roof. I should always get a car at the end of the installation/mapping process.

The installation sequence is required (that's why I thought of streaming it) and next installation may sometimes need a parameter from the pass car instance to perform it's operation.

  1. Is this a good use case for java 8's Stream?

  2. Obvioulsy, my collect at the end is not right. How should I get the car at the end of this installation/assembly line? findFirst().get() will work but I think that's bad, since I should always get a car at the end even if the installation didn't do anything with the carWitEngine and I'm not stream multiple elements.

I'm not sure how cars are assembled but let say you need to put the engine first before adding the interiors for the sake of this analogy

Aucun commentaire:

Enregistrer un commentaire