Related Articles

Related Articles

Kotlin Grouping
  • Last Updated : 17 Sep, 2019

The Kotlin standard library helps in grouping collection elements with the help of extension functions. Grouping means collecting items by category. Here, we have a groupBy() function which takes lambda function and returns a map. In this map, each key is the result of lambda and corresponding value is the list of elements.
We can also use groupBy() function with second lambda expression, which is also called value transformation function. If we use two lambda functions then the produced key of keySelector mapped with the results of value transformation function instead of original elements.

Kotlin program to demonstrate using groupBy() function –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args: Array<String>) {
    val fruits = listOf("apple", "apricot", "banana",
        "cherries", "berries", "cucumber")
    println(fruits.groupBy { it.first().toUpperCase() })
    println(fruits.groupBy(keySelector = { it.first() },
        valueTransform = { it.toUpperCase() }))
}

chevron_right


Output:

{A=[apple, apricot], B=[banana, berries], C=[cherries, cucumber]}
{a=[APPLE, APRICOT], b=[BANANA, BERRIES], c=[CHERRIES, CUCUMBER]}

If we want to apply some operations to group elements then it can be done by applying the function to all group at a time with the help of groupingBy() function. An instance of grouping type will be returned.

We can perform these operations on groups:

  • eachcount(): it counts the items in each group.
  • fold() and reduce(): perform these operation on each group separately and return the result.
  • aggregate(): it is generic way of grouping means applying a specific operation subsequently to all the elements in each group and returns the result. So, it is used to implement custom operations.

Kotlin program to demonstrate groupingBy() function –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(args: Array<String>) {
    val fruits = listOf("apple", "apricot", "banana",
        "cherries", "berries", "cucumber")
    println(fruits.groupingBy { it.first() }.eachCount())
}

chevron_right


Output:

{a=2, b=2, c=2}
My Personal Notes arrow_drop_up
Recommended Articles
Page :