我正在尝试使用 lambda 表达式了解 Java 8 中的方法引用,但遇到了一些我不太明白的问题。
我想将一个方法 (1) 传递到另一个方法 (2) 中,以便方法 2 调用方法 1 并使用方法 1 返回的值。
我在下面设置了一个代码片段,从伪角度来看,它与我想要的非常接近。换句话说,它不符合逻辑,但应该可以轻松理解我想要实现的目标。 handleSomething
方法中的 if (function.run() == true)
部分完全错误,但如上所述,应该指出我想要做什么。
public class Test {
public static void main(String[] args) {
int testValue = 23;
handleSomething(true, testValue, () -> checkIfZero(testValue));
handleSomething(false, testValue, () -> checkIfLargerThanZero(testValue));
}
private static boolean checkIfZero(int value) {
if (value == 0)
return true;
return false;
}
private static boolean checkIfLargerThanZero(int value) {
if (value > 0)
return true;
return false;
}
private static int handleSomething(boolean test, int value, Runnable function) {
if (test) {
System.out.println("Ignore");
return;
}
if (function.run() == true)
System.out.println("Passed");
else
System.out.println("Failed");
}
}
同样,if (function.run() == true)
不起作用,因为 run()
只是从 lambda 表达式调用该方法并且不返回任何东西。
通过此设置执行我想要的操作的一种方法是将对象传递到包含 boolean 值的所有方法中。引用方法可以在对象中设置 boolean 值,并且使用引用方法的方法可以使用该 boolean 值。这种方法有效,但很笨拙,因为我需要将对象从外部传播到方法中。
是否有更简洁的方法来使用 lambda 表达式(而不是创建接口(interface)等)来执行此操作?
最佳答案
使用 @Holger 提议的 BooleanSupplier
是一种可能的解决方案。
但是我建议使用 IntPredicate
,因为这允许您将 testValue 从 handleSomething
传递到谓词:
import java.util.function.IntPredicate;
public class Test {
public static void main(String[] args) {
int testValue = 23;
handleSomething(true, testValue, Test::checkIfZero);
handleSomething(false, testValue, Test::checkIfLargerThanZero);
}
private static boolean checkIfZero(int value) {
if (value == 0)
return true;
return false;
}
private static boolean checkIfLargerThanZero(int value) {
if (value > 0)
return true;
return false;
}
private static void handleSomething(boolean test, int value, IntPredicate function) {
if (test) {
System.out.println("Ignore");
return;
}
if (function.test(value))
System.out.println("Passed");
else
System.out.println("Failed");
}
}
关于使用 lambda 表达式返回结果的 Java 方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49900914/