我正在玩Java 8,以了解如何发挥一流公民的作用。我有以下片段:
package test;
import java.util.*;
import java.util.function.*;
public class Test {
public static void myForEach(List<Integer> list, Function<Integer, Void> myFunction) {
list.forEach(functionToBlock(myFunction));
}
public static void displayInt(Integer i) {
System.out.println(i);
}
public static void main(String[] args) {
List<Integer> theList = new ArrayList<>();
theList.add(1);
theList.add(2);
theList.add(3);
theList.add(4);
theList.add(5);
theList.add(6);
myForEach(theList, Test::displayInt);
}
}
我想做的是使用方法引用displayInt
将方法传递给方法myForEach
。要编译会产生以下错误:
src/test/Test.java:9: error: cannot find symbol
list.forEach(functionToBlock(myFunction));
^
symbol: method functionToBlock(Function<Integer,Void>)
location: class Test
src/test/Test.java:25: error: method myForEach in class Test cannot be applied to given ty
pes;
myForEach(theList, Test::displayInt);
^
required: List<Integer>,Function<Integer,Void>
found: List<Integer>,Test::displayInt
reason: argument mismatch; bad return type in method reference
void cannot be converted to Void
编译器抱怨void cannot be converted to Void
。我不知道如何在签名中指定函数接口的类型,myForEach
以便代码进行编译。我知道我可以简单地将返回类型更改displayInt
为Void
,然后返回null
。但是,在某些情况下,无法更改我想传递到其他地方的方法。有没有简单的方法可以重复使用displayInt
?
Block
已更改为Consumer
JDK 8 API的最新版本