How to transform in ternary operator?

Iván Sánchez Castellanos :

I have an if-then-else statement and I want to transform it to a ternary operator, but I do not know why I cannot do it. The code is the following:

public Movie create(NewMovieDTO newMovieDTO) {
    Movie movieForSaving = NewMovieDTOToMovie.map(newMovieDTO);
    List<Actor> actorsForSaving = new ArrayList<Actor>();

    movieForSaving.getActors().forEach((actor) -> {
        Optional<Actor> actorInDatabase = actorService
            .findByNameAndSurname(actor.getName(), actor.getSurname());

        if(actorInDatabase.isPresent()) {
            actorForSaving.add(actorInDatabase.get());
        } else {
            actorForSaving.add(actor);
        }
    });
    movieForSaving.setActors(actorForSaving);
    return movieRepository.save(movieForSaving);
}

And the code with the ternary operator is:

public Movie create(NewMovieDTO newMovieDTO) {
    Movie movieForSaving = NewMovieDTOToMovie.map(newMovieDTO);
    List<Actor> actorsForSaving = new ArrayList<Actor>();

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

    movieForSaving.setActors(actorForSaving);
    return movieRepository.save(movieForSaving);
}

The following errors are given by the IDE:

Line 1: The target type of this expression must be a functional interface

Line 2: Multiple markers at this line

            - Syntax error, insert "AssignmentOperator Expression" to complete Assignment

            - Syntax error, insert "}" to complete Block

            - actorForSaving cannot be resolved to a variable

            - Syntax error on token(s), misplaced construct(s)

            - actorInDatabase cannot be resolved

            - actorForSaving cannot be resolved

            - Syntax error, insert ";" to complete Statement

Line 3: Syntax error on tokens, delete these tokens.

Is it possible to perform a ternary operator here or how can I solve it?

Thank you so much for your help!

Andrew Tobilko :
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));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=304789&siteId=1