javajava-stream

How save a list of users to database using java 8 streams


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.


Solution

  • I'm pretty sure your code snippet has compilation errors. But there are conceptual problems as well:

    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