I want to be able to send a list of users, loop through each user and if user doesn't exist in database save it and if it exists throw an error.
I have this code so far:
public List<User> addUsers(@RequestBody List<User> userList) {
return userRepository.saveAll(userList);
}
And I would like to apply Java Streams
So far I came to this:
public List<User> addUsers(@RequestBody List<User> userList) {
userList.stream(
.filter(user -> userRepository.findByEmail(user.getEmail()).isPresent(new ResourceAlreadyExistsException("User with", " email s% already exists", user.getEmail())))
).collect(Collectors.toList());
return userRepository.saveAll(userList);
}
It's not working. I am not sure how to do it with streams. Any advice appreciated.
I'm pretty sure your code snippet has compilation errors. But there are conceptual problems as well:
Stream.collect(...)
produces a new list, so in your code snippet you are saving the unmodified userList.User
that already exists it will not provide you with the result you expect since it will stop at the first User
that exists and not go any further. You would have to either change the method to only accept one User
at a time, or modify the return type to something that can indicate whether a User
was saved or not.A correct way to only save and return non-existing User
objects would be for example:
public List<User> addUsers(@RequestBody List<User> userList) {
return userRepository.saveAll(userList.stream()
.filter(user -> !userRepository.findByEmail(user.getEmail()).isPresent())
.collect(Collectors.toList());
}
Here you create a stream from userList
, filter those that can not be found by their email (you could create an existByEmail(...)
method in the userRepository
for this) then you collect it into a List
that is passed straight to the saveAll(...)
method