3

I have a simple loop that adds elements from one list to another list. How can the same result be achieved using streams?

List<User> users = new ArrayList<>();
for(User user: userRepository.findAll()) {
    users.add(user);
}

The reason for doing so is because userRepository.findAll() returns Iterable<User>

3
  • 2
    What's wrong with the code? Why use streams? Commented Mar 6, 2022 at 9:34
  • @Olivier The only reason for using streams is to be better with them. Commented Mar 6, 2022 at 9:36
  • 1
    But it is not "better" with them. Streams are not automatically "better". And in this case, they are not. As you can see, a Stream-based solution is more complicated, and it won't be more efficient. Commented Mar 6, 2022 at 10:16

1 Answer 1

5

spliterator() converts Iterable in stream and then collect it as a List using collect()

List<User> users = 
  StreamSupport.stream(userRepository.findAll().spliterator(), false)
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.