flatMap

Syntax

$collection.flatMap($func)

Description

Applies the function func to each element of the collection collection and smoothes the results into a single collection. If the function returns a collection for an element, all elements of this collection are added to the result. If the function returns a single value, this value is added directly to the result.

This is equivalent to collection.map($func).flatten(), but more efficient as no intermediate collections are created.

Parameters

name Type Type Description Mandatory Default
Collection Collection The input collection whose elements are to be transformed. yes
func Function The function that is applied to each element. The function can return either a collection or a single value. yes

Return value

Type: Collection

A flat collection with the transformed elements.

Examples

Generate multiple values per element

list(1, 2, 3)
    .flatMap(x -> list($x, $x * 10)) 

Output: [1, 10, 2, 20, 3, 30]

For each number, both the original number and the 10-fold value are included in the results list.

Merge lists

list(
  list(1, 2, 3),
  list(4, 5), 
  list(6, 7, 8, 9)
).flatMap(sublist -> $sublist.filter(x -> $x % 2 == 0)) 

Output: [2, 4, 6, 8]

Each sublist is filtered to include only even numbers, then all results are flattened into a single list.

Comparison with map().flatten()

// Statt
list(1, 2).map(x -> list($x, $x * 2)).flatten() 
// Besser
list(1, 2).flatMap(x -> list($x, $x * 2)) 

Advantage: The flatMap variant is more efficient, as no temporary list of lists is created.