为什么Stream :: flatMap的使用错误? [英] Why is this usage of Stream::flatMap wrong?
问题描述
我希望能够像这样使用Stream :: flatMap
I expected to be able to use Stream::flatMap like this
public static List<String> duplicate(String s) {
List<String> l = new ArrayList<String>();
l.add(s);
l.add(s);
return l;
}
listOfStrings.stream().flatMap(str -> duplicate(str)).collect(Collectors.toList());
但我得到以下编译器错误
But I get the following compiler error
Test.java:25:错误:不兼容的类型:无法推断类型变量
R listOfStrings.stream()。flatMap(str - > duplicate(str))。collect (Collectors.toList());
Test.java:25: error: incompatible types: cannot infer type-variable(s) R listOfStrings.stream().flatMap(str -> duplicate(str)).collect(Collectors.toList());
(参数不匹配; lambda表达式中的错误返回类型
List无法转换为Stream)
其中R,T是类型变量:
R extends方法flatMap中声明的Object(函数>)
T扩展在接口Stream中声明的Object
(argument mismatch; bad return type in lambda expression
List cannot be converted to Stream)
where R,T are type-variables:
R extends Object declared in method flatMap(Function>)
T extends Object declared in interface Stream
在scala中我可以做我认为相同的事情
In scala I can do what I believe to be equivalent
scala> List(1,2,3).flatMap(duplicate(_))
res0: List[Int] = List(1, 1, 2, 2, 3, 3)
为什么这不是java中flatMap的有效用法?
Why is this not a valid usage of flatMap in java?
推荐答案
flatMap
需要返回 Stream
,如可以通过 flatMap
的参数看出,其类型为函数<?超级T,?扩展Stream<?扩展R>>
。
The lambda expression in flatMap
needs to return a Stream
, as can be seen by the argument of flatMap
which is of type Function<? super T, ? extends Stream<? extends R>>
.
以下代码将编译并正常运行:
The following code will compile and run fine:
listOfStrings.stream()
.flatMap(str -> duplicate(str).stream()) // note the .stream() here
.collect(Collectors.toList());
因为lambda表达式 str - > duplicate(str).stream <)
的类型为 Function< String,Stream< String>>
。
because the lambda expression str -> duplicate(str).stream()
is of type Function<String, Stream<String>>
.
这篇关于为什么Stream :: flatMap的使用错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!