Flat mapping a series of collections or arrays

Suppose you have a collection where each object has a property that is an array or collection. You can use the flatMap method to create a single List of elements from all the elements on the inner collections. You provide a block that takes the elements of the inner collection and returns them an array or collection. The flatMap method concatenates all the elements in the returned collections or arrays into a single List.

The flatMap method is similar to the array expansion feature of Gosu. However, the flatMap method is available on all collections and arrays. In addition, the flatMap method generates different extracted arrays dynamically using a Gosu block that you provide. Your Gosu block can perform any arbitrary and potentially complex calculation during the flat mapping process.

Example

Suppose your data has the following structure:

  • A claim object has an Exposures property that contains an array of exposure objects.
  • An exposure has a Notes property that contains a list of Note objects.

The Claim.Exposures property is the outer collection of exposures. The Exposure.Notes properties are the inner collections.

First, write a block that extracts the note objects from an exposure object:

\ e -> e.Notes

Next, pass this block to the flatMap method to generate a single list of all notes on the claim:

var allNotes = myClaim.Exposures.flatMap( \ e -> e.Notes )

This code generates a single list that contains all the notes on all the exposures on the claim. In generics notation, the flatMap method returns an instance of List<Note>.

See also