我正在尝试创建一个计时器,以便按计划从 ArrayList 中打印出来。但我收到此错误:
Cannot resolve method 'schedule(<lambda expression>,int,java.util.concurret.TimeUnit)'
为什么我会收到此错误?我该怎么办?
List<String> finalQuestionsList = questionsList;
timer.schedule(()-> finalQuestionsList.forEach(write::println),120, TimeUnit.SECONDS);
最佳答案
JLS断言 lambda 表达式的类型:
A lambda expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.
TimerTask 不是 Function Interface ,因此您不能将 lambda 表达式分配给 TimerTask。但您可以使用适配器方法
task
将 Runnable 适配为 TimerTask。Timer.schedule方法不能采用
TimeUnit
,但您可以使用 TimeUnit.toMills()将持续时间转换为毫秒。我在代码片段中看不到任何
write
变量,因此我使用System.out
来代替。List<String> finalQuestionsList = questionsList; timer.schedule(task(() -> finalQuestionsList.forEach(System.out::println)) , 120, TimeUnit.SECONDS.toMillis(1)); private TimerTask task(Runnable task) { return new TimerTask() { @Override public void run() { task.run(); } }; }
关于Lambda 计划从 ArrayList 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283375/