为什么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的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) 

但它不会很漂亮。