How do you use conditions in lambda expression in java 8?
java, lambda
Solution
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.
Problem
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;