我是编程的新手,我想知道如何使用条件编写lambda表达式。
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
}
}
上面的代码应表示数学函数:
f(x)= x + 4。
所以我的问题是我该如何写一个覆盖此功能的lambda表达式:
f(x)=
x/2(如果x被2整除)
[[x + 1)/2)(否则)
任何帮助表示赞赏:)
编辑:@ T.J。的答案人群拥挤的是我在寻找的东西。
最佳答案
您可以编写带有块主体的lambda({}
)(我称之为“详细lambda”),然后使用return
:
MathInteface f1 = (int x) -> {
if (x % 2 == 0) {
return x / 2;
}
return (x + 1) / 2;
};
或者您使用条件运算符:
MathInteface f1 = (int x) -> (x % 2 == 0) ? x / 2 : (x + 1) / 2;
(或两者)。
在lambda tutorial中有更多详细信息。
关于java - 如何在Java 8中的lambda表达式中使用条件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43834856/