As per the documentation on Oracle's website:
Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.
Does this include saving elements of the stream to a database?
Imagine the following (pseudo) code:
public SavedCar saveCar(Car car) {
SavedCar savedCar = this.getDb().save(car);
return savedCar;
}
public List<SavedCars> saveCars(List<Car> cars) {
return cars.stream()
.map(this::saveCar)
.collect(Collectors.toList());
}
What are the unwanted effects opposed to this implementation:
public SavedCar saveCar(Car car) {
SavedCar savedCar = this.getDb().save(car);
return savedCar;
}
public List<SavedCars> saveCars(List<Car> cars) {
List<SavedCars> savedCars = new ArrayList<>();
for (Cat car : cars) {
savedCars.add(this.saveCar(car));
}
return savedCars.
}
No storage. Streams don't have storage for values; they carry values from a source (which could be a data structure, a generating function, an I/O channel, etc) through a pipeline of computational steps.
A stream does not store data and, in that sense, is not a data structure.
This lets us take advantage of one of the key differences between a Stream and a Collection in Java – while Collections represent a set of data stored entirely in memory, Streams are simply storage-agnostic series of data.
If you have a small list, loops perform better. If you have a huge list, a parallel stream will perform better. Purely thinking in terms of performance, you shouldn't use a for-each loop with an ArrayList, as it creates an extra Iterator instance that you don't need (for LinkedList it's a different matter).
The absolute easiest example is:
cars.stream()
.map(this:saveCar)
.count()
In this case, from java-9 and up, map
will not be executed; since you do not need it to know the count
, at all.
There are other multiple cases where side effects would cause you lots of pain; under certain conditions.
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