为什么 Stream::flatMap 的这种用法是错误的?错误、Stream、flatMap

2023-09-07 01:41:56 作者:我是全球绝版仅此一款

我希望能够像这样使用 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 表达式中的返回类型错误列表无法转换为流)其中 R,T 是类型变量:R 扩展了在方法 flatMap(Function>) 中声明的对象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 类型的参数 Function<?超级T,?扩展流