Home » Java » How do you use conditions in lambda expression in java 8?

How do you use conditions in lambda expression in java 8?

Posted by: admin December 28, 2021 Leave a comment

Questions:

I am beginner in programming and I was wondering how you can write lambda expressions with conditions.

public interface MathInterface {

    public int retValue(int x);

}

public class k1{
public static void main(String [] args) {
MathInterface f1 = (int x) -> x + 4; // this is a normal lambda expression
    }
}

The code above should represent the mathematical function:

f(x) = x + 4.

So my question is how can i write a lambda expression that covers this function:

f(x) =

x/2 (if x is divisble by 2)

((x + 1)/2) (otherwise)

any help appreciated 🙂

Edit: The answer from @T.J. Crowder was, what I was searching.

MathInteface f1 = (int x) -> (x % 2 == 0) ? x / 2 : (x + 1) / 2;

Answers:

So my question is how can i write a lambda expression that covers this function…

You either write a lambda with a block body ({}) (what I call a “verbose lambda”) and use return:

MathInteface f1 = (int x) -> {
    if (x % 2 == 0) {
        return x / 2;
    }
    return (x + 1) / 2;
};

or you use the conditional operator:

MathInteface f1 = (int x) -> (x % 2 == 0) ? x / 2 : (x + 1) / 2;

(or both).

More details in the lambda tutorial.

###

For that particular function, a ternary would be possible.

(int x) -> x % 2 == 0 ?  x/2 : (x+1)/2;

Otherwise, make a block

(int x) -> {
    // if... else 
} 

Inside of which, you return the value

###

This return an integer :

public static void main(String [] args) {
    MathInterface f1 = (int x) -> (x%2 ==0) ? x/2 : ((x + 1)/2); 
}

###

If you feel like being cheeky, you can actually exploit integer division here.

When you divide two integers, the part of the number after the decimal point is automatically dropped. So 5 / 2 = 2.

For that reason, you can get away with just the odd number case:

MathInterface f1 = (int x) -> (x + 1) / 2;

In the case of even numbers, when they are incremented they will become odd, resulting in a .5 which will be dropped automatically.


I wouldn’t recommend this approach because it’s not clear you (the original programmer) are aware what’s going on. Being explicit is better.