How to transform in ternary operator?

actorForSaving.add(actorInDatabase.isPresent() ? actorInDatabase.get() : actor);

The ternary operator can't be a statement, it's an expression that returns something. In your case, actorInDatabase.isPresent() ? actorInDatabase.get() : actor returns an Actor.

Another good alternative would be using Optional#orElse as -

actorForSaving.add(actorInDatabase.orElse(actor));

Your if is just fine. But if you really want to use the conditional operator here, the way to do it is to do it within the argument list to add:

movieForSaving.getActors().forEach((actor) -> {
    Optional<Actor> actorInDatabase = actorService.findByNameAndSurname(actor.getName(), actor.getSurname());                        
    actorForSaving.add(actorInDatabase.isPresent() ? actorInDatabase.get() : actor);
});

You may also be able to use orElse. But your question seemed to be specifically about the conditional operator. (Which is a ternary operator — an operator accepting three operands — but not the ternary operator. Granted at the moment it's Java's only ternary operator, but in theory another could be added.)


The error was already explained. Just the Streamy way to use all and Optional:

Movie movieForSaving = NewMovieDTOToMovie.map(newMovieDTO);
List<Actor> actorsForSaving = movieForSaving.getActors().stream()
        .map(actor -> actorService.findByNameAndSurname(actor.getName(),
                 actor.getSurname()).orElse(actor))
        .collect(Collectors.toList());

movieForSaving.setActors(actorForSaving);