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;
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.
This return an integer :
public static void main(String [] args) {
MathInterface f1 = (int x) -> (x%2 ==0) ? x/2 : ((x + 1)/2);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With