为什么 Stream.flatMap 不能接受集合?



给定以下数据类示例:

class Country {
List<Region> regions = new ArrayList<>();
List<Region> getRegions() {
return regions;
}
}
class Region {
String getName() {
return "some name";
}
}

假设我会有一份国家名单

List<Country> countries = new ArrayList<>();

我想将这些流式传输到他们的地区和相应的名称,我想做以下操作:

countries.stream().flatMap(Country::getRegions).map(Region::getName)...

然而,该代码不会编译,因为"getRegions"的返回值是Collection(List),而不是flatMap方法接受的Stream。但是,既然我知道任何Collection都可以通过它的Collection.stream()方法进行流式传输,那应该不是问题。尽管如此,我还是不得不这样写:

countries.stream().flatMap(c -> c.getRegions().stream()).map(Region::getName)...

与前者相比,后者(在更丰富的上下文中)可读性差得多。

问题是,有什么原因让我错过了,让它这么笨重吗?在我们的框架中,我有很多例子表明,我被迫走上这条路,总是让我尝到酸味。(我想我只需要把Kotlin添加到我们的项目中,并用一个采用Collection:p或do I的flatMap方法扩展Stream类?)

一个技术原因,这并不理想,但可能是没有做到这一点的原因。在Java中,不能重载泛型类型。

他们需要支持

Stream.flatMap(Function<Object, Stream<X>> function)

这意味着他们不能用超载

Stream.flatMap(Function<Object, Collection<X>> function)

因为这两种方法在擦除之后具有相同的签名。

他们可以添加一种方法

Stream.flatMapCollection(Function<Object, Collection<X>> function)

Stream.flatMapIterable(Function<Object, Iterable<X>> function)
Stream.flatMapI(Function<Object, Iterable<X>> function)

但那就不好看了。

最新更新