Replace lambda with method reference in flatMap while displaying array

Say we have a Customer class:

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

and the set of customers that we need to match on cars.

I am currently doing it something like this:

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

It works well, but the code does not look elegant . I would really like to replace it with code that uses links to methods that usually look more readable and more compact. But using an array type field makes it difficult to work.

Question: is there a way to increase the call to flatMap so that it is more readable / compact / understandable?

+5
source share
3 answers

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

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

Just add a Customer method that returns a Car s stream. Using typical naming conventions, it will look like

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

Then you can use it as

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

Generally, properties of a mutable type, such as an array, should be handled with care. The only way to prevent modification through a getter is to make a copy. Thus, providing an alternative method that returns a read-only type, such as Stream , which does not need to be copied, has additional capabilities, in addition to creating a neat flatMap .

+6
source

You can use:

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

But I do not think it is more elegant . And also, having everything, like methods like these, makes it less readable, at least for me. I have to explain to myself why I see this to be less readable, because there are two steps that I need to understand when reading this code. why map done and why flatMap done - it may seem insignificant though.

+3
source

Source: https://habr.com/ru/post/1274247/


All Articles