Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

lambda

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;

like image 422
Iduens Avatar asked May 07 '17 18:05

Iduens


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

like image 145
T.J. Crowder Avatar answered Nov 14 '22 23:11

T.J. Crowder


This return an integer :

public static void main(String [] args) {
    MathInterface f1 = (int x) -> (x%2 ==0) ? x/2 : ((x + 1)/2); 
}
like image 24
A Monad is a Monoid Avatar answered Nov 14 '22 23:11

A Monad is a Monoid


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

like image 29
OneCricketeer Avatar answered Nov 14 '22 23:11

OneCricketeer