在数组映射期间将 lambda 替换为 flatMap 中的方法引用

Replace lambda with method reference in flatMap during array mapping

假设我们有一个 Customer class:

public class Customer {
    private Car[] cars;
    // getter, setter, constructor
}

以及我们需要在汽车上映射的客户集合。

目前我正在这样做:

Collection<Customer> customers = ...
customers.stream().flatMap(
        customer -> Arrays.stream(customer.getCars())
)...

它运行良好,但是代码看起来不优雅。我真的很想用使用通常看起来更具可读性和更紧凑的方法引用的代码替换它。但是使用数组类型的字段就很难了。

问题: 有没有什么方法可以增强 flatMap 的调用,使其更 readable/compact/clear?

您可以将 flatMap 调用拆分为两个调用 - mapflatMap - 每个调用接收一个方法引用:

Collection<Customer> customers = ...
customers.stream()
         .map(Customer::getCars)
         .flatMap(Arrays::stream)...

您可以使用:

 .map(Customer::getCars)
 .flatMap(Arrays::stream)

但我不认为这在任何方面都更 elegant。并且将所有内容都作为这样的方法引用会使它的可读性降低,至少对我而言是这样。我应该自己解释一下为什么我认为它的可读性较差,因为在阅读这段代码时我现在需要理解两个阶段。为什么 map 完成以及为什么 flatMap 完成 - 虽然看起来很小。

只需向 Customer 添加一个返回 Car 流的方法。使用典型的命名约定,它看起来像

public Stream<Car> cars() {
    return Arrays.stream(cars);
}

那么,你可以像这样使用它

customers.stream().flatMap(Customer::cars)

通常,应谨慎处理数组等可变类型的属性。防止通过 getter 修改的唯一方法是复制。因此,提供一种替代方法返回只读类型,如 Stream,它不需要复制,除了使 flatMap 整洁之外还有其他用途。