Advantages of Stream and Spring Data

前端 未结 3 1203
灰色年华
灰色年华 2021-02-20 12:13

Some people override the CrudRepository\'s method findAll to return an Stream (java 8), but I saw they finally transform the Stream to a List in order to send it through a rest

3条回答
  •  心在旅途
    2021-02-20 12:49

    Providing it as a Stream gives the repository consumer the choice on how to collect the data. In addition it allows chaining/piping of operations on the stream, such as mapping to DTOs, augmenting data, and filtering. If the only thing you're ever going to do is collect it to a list and send as a response, then there is no benefit.

    But take for example the case where a Thing repository returns a List findAllThings() of n Thingss because most of the time it's just sent as a list via the API. But then someone builds a service in the application that needs to filter only Things that exist in another set of m Things in the application. We would have to recreate a list filtering on the set like

    List acceptedThings = repo.findAllThings()
                                     .stream()
                                     .map(t->set.contains(t))
                                     .collect(toList());
    

    So we've had to iterate the original list and reconstruct a new list. If there are further operations on this list, you can see how it may be sub-optimal.

    If the response from the repository had been Stream then we could have chained the filter operation and passed on the Stream for any further processing.

    Stream acceptedThings = repo.findAllThings()
                                       .map(t->set.contains(t));
    

    Only right at the end when something consumes the stream will execute all the operations relevant for each item. This is much more efficient as each element only needs to be visited at most once and no intermediate collections need to be created.

    Given that Spring now supports returning Streams as @ResponseBody's in controllers, it's even better.

提交回复
热议问题