JAVA8中多个if else if与&&条件

Jac*_*kie 6 java java-8

我想在 java 8 最佳代码实践中转换以下代码

if(i==0 && j==0) {
    return 1;    
} else if (i==0 && j==1) {
    return 2;
} else if (i==1 && j==0) {
    return 3;
} else if (i==1 && j==1) {
    return 4;
} 
Run Code Online (Sandbox Code Playgroud)

编辑: OP 作为对问题的评论发布

if(counterFlag==0 && priorityEnable==0) { 
    return 0; 
} else if (counterFlag==0 && priorityEnable==1) { 
    return 1; 
} else if (counterFlag==1 && priorityEnable==0) { 
    return 2; 
} else { 
    return 3; 
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*aye 1

注意:在您的示例中,您返回 3 作为默认值,因此如果i=2j=2例如您将返回3. 这是预期的行为吗?i我将提供示例,其中和的值j被假设始终为01

对于您的具体示例:

这似乎是一个很好的妥协,它更短且易于阅读:

if(counterFlag==0) {
    return priorityEnable == 0 ? 0 : 1;
}
return priorityEnable == 0 ? 2 : 3;
Run Code Online (Sandbox Code Playgroud)

对于更复杂的情况(即 3、4 或更多变量): 我会选择这样的方法:

Map<int[], Integer> map = new HashMap<>();
map.put(new int[] {0, 0}, 0);
map.put(new int[] {0, 1}, 1);
map.put(new int[] {1, 0}, 2);
map.put(new int[] {1, 1}, 3);

return map.entrySet().stream()
        .filter(e -> e.getKey()[0] == counterFlag)
        .filter(e -> e.getKey()[1] == priorityEnable)
        .map(Map.Entry::getValue)
        .findFirst()
        .orElseThrow(IllegalArgumentException::new);
Run Code Online (Sandbox Code Playgroud)

编辑: @Holger 指出“使用 HashMap 然后线性搜索它是一种浪费。使用 IntBuffer 作为键,您可以通过 get 执行直接查找”

这是一个很好的观点,我尝试了一下,我认为这就是他的意思:

Map<IntBuffer, Integer> map = new HashMap<>();
map.put(IntBuffer.wrap(new int[] {0, 0}), 0);
map.put(IntBuffer.wrap(new int[] {0, 1}), 1);
map.put(IntBuffer.wrap(new int[] {1, 0}), 2);
map.put(IntBuffer.wrap(new int[] {1, 1}), 3);

IntBuffer intBuffer = IntBuffer.wrap(new int[] {counterFlag, priorityEnable});
return map.get(intBuffer);
Run Code Online (Sandbox Code Playgroud)