假设我们有一个 Customer
类:
public class Customer {
private Car[] cars;
// getter, setter, constructor
}
以及我们需要在汽车上映射的客户集合。
目前我正在这样做:
Collection<Customer> customers = ...
customers.stream().flatMap(
customer -> Arrays.stream(customer.getCars())
)...
它运行良好,但代码看起来不优雅。我真的很想用使用通常看起来更具可读性和更紧凑的方法引用的代码替换它。但是使用数组类型的字段就很难了。
问题有什么方法可以增强 flatMap
调用,使其更易读/更紧凑/更清晰?
最佳答案
您可以将 flatMap
调用拆分为两个调用 - map
和 flatMap
- 每个调用都接收一个方法引用:
Collection<Customer> customers = ...
customers.stream()
.map(Customer::getCars)
.flatMap(Arrays::stream)...
关于java - 在数组映射期间将 lambda 替换为 flatMap 中的方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47923096/