I am trying to do what seems to be a relatively basic thing in the new JDK 8 land of functional programming, but I can't get it to work. I have this working code:
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class so1 {
public static void main() {
List<Number> l = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Callable<Object>> checks = l.stream().
map(n -> (Callable<Object>) () -> {
System.out.println(n);
return null;
}).
collect(Collectors.toList());
}
}
It takes a list of numbers and produces a list of functions that can print them out. However, the explicit cast to Callable seems redundant. It seems to me and to IntelliJ. And we both agree that this should also work:
List<Callable<Object>> checks = l.stream().
map(n -> () -> {
System.out.println(n);
return null;
}).
collect(Collectors.toList());
However I get an error:
so1.java:10: error: incompatible types: cannot infer type-variable(s) R
List<Callable<Object>> 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 <R>map(Function<? super T,? extends R>)
T extends Object declared in interface Stream
1 error
map(..)
.l.stream().<Callable<Object>> map(...)
– Sarsenet