What are recommendations when to define method list and stream in Spring Data repository?
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-streaming
Example:
interface UserRepository extends Repository<User, Long> {
List<User> findAllByLastName(String lastName);
Stream<User> streamAllByFirstName(String firstName);
// Other methods defined.
}
Please, note, here I am not asking about Page, Slice - they are clear to me, and I found their description in the documentation.
My assumption (am I wrong?):
Stream does not load all the records into Java Heap. Instead it loads
krecords into the heap and processes them one by one; then it loads anotherkrecords and so on.List does load all the records into Java Heap at once.
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.
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.
I saw that some developers collect the stream into a list before returning a response.
class UserController {
public ResponseEntity<List<User>> 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);
}
}
For this case, I do not see any advantage of Stream, using list will make the same end result.
Are then any examples when using list is justified?