title: Spring Data repository: list vs stream
body: <p>What are recommendations when to define method <code>list</code> and <code>stream</code> in Spring Data repository?</p>
  <p><a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-streaming" rel="noreferrer">https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-streaming</a></p>
  <p>Example:</p>
  <pre><code>interface UserRepository extends Repository&lt;User, Long&gt; {
  
    List&lt;User&gt; findAllByLastName(String lastName);
  
    Stream&lt;User&gt; streamAllByFirstName(String firstName);                    
           
    // Other methods defined.
  }
  </code></pre>
  <p>Please, note, here I am not asking about <strong>Page</strong>, <strong>Slice</strong> - they are clear to me, and I found their description in the <a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.special-parameters" rel="noreferrer">documentation</a>.</p>
  <hr />
  <p>My assumption (am I wrong?):</p>
  <ol>
  <li><p>Stream does not load all the records into Java Heap. Instead it loads <code>k</code> records into the heap and processes them one by one; then it loads another <code>k</code> records and so on.</p>
  </li>
  <li><p>List does load all the records into Java Heap at once.</p>
  </li>
  <li><p>If I need some background batch job (for example calculate analytics), I could use stream operation because I will not load all the records into the heap at once.</p>
  </li>
  <li><p>If I need to return a REST response with all the records, I will need to load them into RAM anyway and serialize them into JSON. In this case, it makes sense to load a list at once.</p>
  </li>
  </ol>
  <hr />
  <p>I saw that some developers collect the stream into a list before returning a response.</p>
  <pre><code>class UserController {
  
      public ResponseEntity&lt;List&lt;User&gt;&gt; getUsers() {
          return new ResponseEntity(
                  repository.streamByFirstName()
                          // OK, for mapper - it is nice syntactic sugar. 
                          // Let's imagine there is not map for now...
                          // .map(someMapper)  
                         .collect(Collectors.toList()), 
                  HttpStatus.OK);
      }
  }
  </code></pre>
  <p>For this case, I do not see any advantage of Stream, using <code>list</code> will make the same end result.</p>
  <p>Are then any examples when using <code>list</code> is justified?</p>