Open In App

Kotlin Grouping

Improve
Improve
Like Article
Like
Save
Share
Report

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 –




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() }))
}


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 –




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


Output:

{a=2, b=2, c=2}

Last Updated : 17 Sep, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads