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?
The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.
If you are using a lambda expression as an anonymous function but not doing anything with the argument passed, you can replace lambda expression with method reference. In the first two cases, the method reference is equivalent to lambda expression that supplies the parameters of the method e.g. System.
map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value.
In Java 8 Streams, the flatMap() method applies operation as a mapper function and provides a stream of element values. It means that in each iteration of each element the map() method creates a separate new stream. By using the flattening mechanism, it merges all streams into a single resultant stream.
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)...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With