我正在尝试执行新的JDK 8函数式编程领域中似乎是相对基本的事情,但是我无法使其工作。我有这个工作代码:
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class so1 {
public static void main() {
List l = new ArrayList<>(Arrays.asList(1, 2, 3));
List> checks = l.stream().
map(n -> (Callable) () -> {
System.out.println(n);
return null;
}).
collect(Collectors.toList());
}
}
它接受一个数字列表,并产生可以打印出来的功能列表。但是,显式转换为Callable似乎是多余的。在我和IntelliJ中看来。我们都同意这也应该起作用:
List> checks = l.stream().
map(n -> () -> {
System.out.println(n);
return null;
}).
collect(Collectors.toList());
但是我得到一个错误:
so1.java:10: error: incompatible types: cannot infer type-variable(s) R
List> checks = l.stream().map(n -> () -> {System.out.println(n); return null;}).collect(Collectors.toList());
^
(argument mismatch; bad return type in lambda expression
Object is not a functional interface)
where R,T are type-variables:
R extends Object declared in method map(Function super T,? extends R>)
T extends Object declared in interface Stream
1 error