Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform in ternary operator?

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!

like image 312
Iván Sánchez Castellanos Avatar asked Oct 01 '19 09:10

Iván Sánchez Castellanos


People also ask

How do you write a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

What is ternary operator with example?

A ternary operator lets you assign one value to the variable if the condition is true, and another value if the condition is false. The if else block example from above could now be written as shown in the example below. var num = 4, msg = ""; msg = (num === 4) ?

What does ternary operator return?

The ternary operator is used to return a value based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.

How do you use else IFN ternary operator?

The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .


3 Answers

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));
like image 132
Andrew Tobilko Avatar answered Oct 20 '22 05:10

Andrew Tobilko


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.)

like image 41
T.J. Crowder Avatar answered Oct 20 '22 03:10

T.J. Crowder


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);
like image 2
Joop Eggen Avatar answered Oct 20 '22 03:10

Joop Eggen