1

Is there any advantage of using stream filter operation over iterator with continue operation?

Example for iteration:

for (ApiSite apiSite : sites) {
    Site mSite = Site.getSiteByName(apiSite.getName());
    if (mSite == null || deletedSitesToSkip.contains(mSite)) {
        LOGGER.info("Skipping site: {} as this has been deleted ", apiSite.getName());
        continue;
    }
    // operation
}

stream with filter example:

sites.stream().filter(apiSite -> {
    Site mSite = Site.getSiteByName(apiSite.getName());
    return (mSite != null && !deletedSitesToSkip.contains(mSite));
}).map(//some operation);
nitishagar
  • 9,038
  • 3
  • 28
  • 40

2 Answers2

3

First, the filter behavior depends on which terminal operation is invoked.

  • IF a short-circuiting terminal operation, e.g:anyMatch is invoked, the filter will be exit until the first satisfied element.

  • IF a non-short-circuiting terminal operation, e.g:count, collect is invoked, the filter's behavior just like as yours. continue and process the next until the last.

Second, the stream api will make your code more expressive.

Third, Stream api allows you do some time-consuming operations in parallel . but for loop will take more effort to do it, for example:

stream.parallel().map(it-> remoteCall(it)).collect(...);

Fourth, Stream operation can be serialized, cached, the apache spark core & streaming api is a framework that processing distributed operations on nodes in a cluster.

holi-java
  • 29,655
  • 7
  • 72
  • 83
1

The stream version has better semantics: you clearly operate on a set of data, filter it by a condition, and apply an operation on the matching elements. This adds to the readability, and allows to easily extend the processing by elementar building blocks (filter, map) without the risk of breaking much (maintainability).

Moreso, the streams operations (for filtering, mapping, ...) can be designed as reusable building blocks (DRY principle), which can be individualy tested, thus gaining reliability.

All in all, those are non-functional benefits (the functionality of both variants is the same), adding to the quality of the code.

Besides, continue is worth avoiding completely, as it quickly leads to awkward code when nesting loop blocks, making it hard to read and maintain.

Peter Walser
  • 15,208
  • 4
  • 51
  • 78