I have the following bit of simplified code that fails to compile and I don't understand why:
List<Optional<Integer>> list =
new ArrayList<>();
List<Integer> flattened =
list
.stream()
.flatMap(i -> i)
.collect(Collectors.toList());
The compiler tells me:
[ERROR] ... incompatible types: cannot infer type-variable(s) R
[ERROR] (argument mismatch; bad return type in lambda expression
[ERROR] Optional<Integer> cannot be converted to Stream<? extends R>)
[ERROR] where R,T are type-variables:
[ERROR] R extends Object declared in method <R>flatMap(Function<? super T,? extends Stream<? extends R>>)
[ERROR] T extends Object declared in interface Stream
I admit I'm not used to Java but I have to for a project. I mocked this in Scala where list.flatten
and the equivalent list.flatMap(i => i)
work just as expected:
val list = List(Some(1), Some(2), None)
list.flatten // List(1, 2)
Is Java's flatMap
different?