Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java 8: How can i refactor a simple for loop using functional operations (streams)

My IDE is trying to tell me that there is a better way of performing certain loops by using functional operations like streams introduced in Java 8. I’ve never gotten much into streams and when i attempted to, i struggled understanding the gist of it. Even after watching Programming with Streams in Java 8 | Venkat Subramaniam.

I read some guides and posts and tried to refactor a simple for loop using streams:

for (Customer c : this.customers) customerRepo.save(c);

to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.customers.stream().map(c -> customerRepo.save(c));

I don’t get any warnings while compiling and also no exceptions when i run it. Still, it doesn’t seem to work and no records are being saved to my db. I think i did something wrong here and i’d appreciate it if someone would correct me.

>Solution :

A stream should contain a terminal operation in order to be executed (like collect, reduce, forEach, etc.). Your stream lacks one.

Here’s a quote from the documentation:

To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

And you don’t need a stream in this case, instead you can use Iterable.forEach(), by invoking forEach() on the collection of customers:

customers.forEach(c -> customerRepo.save(c));

The same can be written using a method reference:

customers.forEach(customerRepo::save);

For more information, refer to:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading