1

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>

Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
Kristjan
  • 49
  • 1
  • 6
  • 2
    What's wrong with the code? Why use streams? – Olivier Mar 06 '22 at 09:34
  • @Olivier The only reason for using `streams` is to be better with them. – Kristjan Mar 06 '22 at 09: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. – Stephen C Mar 06 '22 at 10:16

1 Answers1

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());
Krishna Majgaonkar
  • 1,532
  • 14
  • 25