aggregate

inline fun <T, K, R> Grouping<T, K>.aggregate(operation: (key: K, accumulator: R?, element: T, first: Boolean) -> R): Map<K, R>(source)

Groups elements from the Grouping source by key and applies operation to the elements of each group sequentially, passing the previously accumulated value and the current element as arguments, and stores the results in a new map.

The key for each element is provided by the Grouping.keyOf function.

Since Kotlin

1.1

Return

a Map associating the key of each group with the result of aggregation of the group elements.

Parameters

operation

function is invoked on each element with the following parameters:

  • key: the key of the group this element belongs to;

  • accumulator: the current value of the accumulator of the group, can be null if it's the first element encountered in the group;

  • element: the element from the source being aggregated;

  • first: indicates whether it's the first element encountered in the group.

Samples


fun main() { 
   //sampleStart 
   val numbers = listOf(3, 4, 5, 6, 7, 8, 9)

val aggregated = numbers.groupingBy { it % 3 }.aggregate { key, accumulator: StringBuilder?, element, first ->
    if (first) // first element
        StringBuilder().append(key).append(":").append(element)
    else
        accumulator!!.append("-").append(element)
}

println(aggregated.values) // [0:3-6-9, 1:4-7, 2:5-8] 
   //sampleEnd
}
inline fun <T, K, R> Grouping<T, K>.aggregate(operation: (key: K, accumulator: R?, element: T, first: Boolean) -> R): Map<K, R>(source)

Groups elements from the Grouping source by key and applies operation to the elements of each group sequentially, passing the previously accumulated value and the current element as arguments, and stores the results in a new map.

The key for each element is provided by the Grouping.keyOf function.

Since Kotlin

1.1

Return

a Map associating the key of each group with the result of aggregation of the group elements.

Parameters

operation

function is invoked on each element with the following parameters:

  • key: the key of the group this element belongs to;

  • accumulator: the current value of the accumulator of the group, can be null if it's the first element encountered in the group;

  • element: the element from the source being aggregated;

  • first: indicates whether it's the first element encountered in the group.

Samples


fun main() { 
   //sampleStart 
   val numbers = listOf(3, 4, 5, 6, 7, 8, 9)

val aggregated = numbers.groupingBy { it % 3 }.aggregate { key, accumulator: StringBuilder?, element, first ->
    if (first) // first element
        StringBuilder().append(key).append(":").append(element)
    else
        accumulator!!.append("-").append(element)
}

println(aggregated.values) // [0:3-6-9, 1:4-7, 2:5-8] 
   //sampleEnd
}