有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java8中,如何使用lambda表达式中的条件?

我是编程初学者,我想知道如何用条件编写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.Crowder的答案是,我在搜索什么

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


共 (4) 个答案

  1. # 1 楼答案

    对于那个特定的函数,三元函数是可能的

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

    否则,制造块

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

    在其中,您return该值

  2. # 2 楼答案

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

    您可以使用块体({})(我称之为“详细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

  3. # 3 楼答案

    如果你想变得厚颜无耻,你实际上可以在这里利用整数除法

    当您除以两个整数时,小数点后的数字部分将自动删除。所以{}

    因此,您可以只使用奇数情况:

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

    在偶数的情况下,当它们递增时,它们将变为奇数,导致.5将自动删除


    我不推荐这种方法,因为不清楚您(最初的程序员)是否知道发生了什么。直言不讳更好

  4. # 4 楼答案

    这将返回一个整数:

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