简体   繁体   中英

Error using a ternary operator

As shown in the following code, I would like to use ternary operator. But I am getting an error saying: "; expected" but I think, there is no need to add the semi-colon.

Code :

.filter(new Predicate<List<String>>() {
    @Override
    public boolean test(@NonNull List<String> strings) throws Exception {
        List<String> lst = new ArrayList<String>();
        for (String string : strings) {
            Log.i(TAG, ".filter(): string: " + string);
            string.toLowerCase().startsWith("b") ? lst.add(string): continue;
        }
        Log.i(TAG, ".filter(): lsr: " + lst);
        return lst.size() > 0;
    }
})

Ternary operation is used to assign or return values, continue; is an instruction, to keep it simple use something like:

if(string.toLowerCase().startsWith("b")) {
    lst.add(string); 
} else {  
    continue;
}

First of all, you cannot use continue in a ternary condition, since continue is a statement, not an expression, as what the ternary condition is expecting. More on the expression statements here (credits to @Andreas )

My suggestion instead of trying to try making use of the ternary condition, is to use java streams, since you are already using filter and predicates:

.filter(strings -> strings.stream()
                          .anyMatch(string -> string.toLowerCase().startsWith("b")));

This will have the same result you are trying to do with collecting the strings that start with b .

The Conditional Operator ? : ? : is an expression , not a statement (see JLS 15.25. Conditional Operator ? : ).

Expressions cannot be written as statement, ie the following are both invalid:

2 + 7;
a == 42 ? foo() : bar();

Note that only some expressions are also valid as statements, and ? : ? : is not one of them ( JLS 14.8. Expression Statements ):

 ExpressionStatement: StatementExpression ; StatementExpression: Assignment PreIncrementExpression PreDecrementExpression PostIncrementExpression PostDecrementExpression MethodInvocation ClassInstanceCreationExpression 

In addition, the syntax of the Conditional Operator is:

 ConditionalOrExpression ? Expression : ConditionalExpression ConditionalOrExpression ? Expression : LambdaExpression 

Meaning that all 3 parts must be expressions , and continue is a statement, not an expression.

To summarize, ? : ? : is an expression and cannot be used as a statement, and it can only contain expressions, not statements. It is not a replacement for the if statement.

So, your code should be written using if statement:

for (String string : strings) {
    Log.i(TAG, ".filter(): string: " + string);
    if (string.toLowerCase().startsWith("b")) {
        lst.add(string);
    } else {
        continue;
    }
}

Of course, having a continue statement at the end of the loop is redundant (the loop will continue anyway), so the else can be removed:

for (String string : strings) {
    Log.i(TAG, ".filter(): string: " + string);
    if (string.toLowerCase().startsWith("b"))
        lst.add(string);
}

First of all Ternary operation is used to assign or return values, continue is an instruction.

string.toLowerCase().startsWith("b") ? lst.add(string): continue;

Replace this line by

if(string.toLowerCase().startsWith("b"))
     lst.add(string);
else
     continue;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM