Replace lambda with method reference in flatMap during array mapping

Sasha Shpota :

Say we have a Customer class:

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

and collection of customers which we need to map on cars.

Currently I'm doing it somehow like this:

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

It works well, but the code doesn't look elegant. I'd really like to replace it with code that uses method references which usually looks more readable and more compact. But using a field of array type makes it hard.

Question: is there any way of enhancing the flatMap call so it will be more readable/compact/clear?

Eran :

You can split the flatMap call into two calls - map and flatMap - each receiving a method reference:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=441229&siteId=1