"flat" map method

Stefan Springer stefan.springer1 at googlemail.com
Wed Jun 22 13:03:52 PDT 2011


Yes, as I said I know you could use a map/reduce combination, but this
gets cumbersome when you do this several level deep:

myList.flatMap(#{x ->
   x.flatMap(#{x ->
      ...
  })
})

2011/6/22 Brian Goetz <brian.goetz at oracle.com>

> This can be implemented by:
>
>  List<T> foo = ...
>  Mapper<T, List<U>> mapper = ...
>  Reducer<List<U>, List<U>> listJoiner = ...
>  List<U> flattened =
>      foo.map(mapper)
>         .reduce(Collections.emptyList(**), listJoiner);
>
> If the intermediate form is a collection that admits an efficient union
> operation, there's no reason this can't be efficient as well.
>
>
> On 6/22/2011 3:43 PM, Stefan Springer wrote:
>
>> The "classical" map method on a Collection<T>  receives a closure { T =>
>>  U }
>> giving a Collection<U>. What I am missing in all discussions is some kind
>> of
>> a "flat" map method receiving a closure { T =>  Collection<T>  } resulting
>> in
>> a concatenation Collection<T>  of all individual Collection<T>  results
>> for
>> each member of the original Collection<T>. I know that could be realized
>> by
>> combining the map method with a reduce method, but for easy coding I think
>> such a "flatMap" method would be very nice. I know this pattern from the
>> XML/SGML transformation language MetaMorphosis where such a "flattening"
>> is
>> very appropriate. Would vote for adding such a method for collections in
>> Java 8.
>>
>>


More information about the lambda-dev mailing list