Design Converter
Education
Last updated on Sep 27, 2024
Last updated on Sep 2, 2024
Software Development Executive - III
When working with collections in Kotlin, grouping elements based on certain criteria is a common task. The Kotlin standard library provides a powerful and flexible groupBy function to help you group elements in a collection based on a specified key. Understanding how to use groupBy effectively can save time and make your code cleaner and more efficient.
In this detailed guide, we'll explore how to use Kotlin groupBy, examine various examples, and cover the technical details you need to know to perform operations efficiently.
The groupBy function in Kotlin is an extension function available in the standard library that allows you to group elements of a collection by the result of a given lambda function. The function returns a Map where each key is the result of the lambda function (known as the lambda result), and the corresponding value is a list of elements that match that key. This is particularly useful when you need to group collections based on certain properties or criteria.
• Returns a Map: The groupBy function returns a map where the keys are computed using a lambda expression and the values are lists of elements that match those keys.
• Flexible and Easy to Use: You can use groupBy with any type of collection, such as List, Set, or any other iterable.
• Supports Nested Grouping: You can easily group elements based on complex conditions using nested groupBy functions.
The groupBy function in Kotlin works by taking a collection of elements and a lambda argument to determine the key for each group. It then returns a map where each key results from the lambda argument, and the value is a list of elements that correspond to that key. Let's look at a simple example to understand this better.
Consider a list of words and you want to group them by their first letter:
1val words = listOf("apple", "banana", "apricot", "blueberry", "cherry") 2 3val groupedByFirstLetter = words.groupBy { it.first() } 4println(groupedByFirstLetter)
Output:
1{a=[apple, apricot], b=[banana, blueberry], c=[cherry]}
The above code uses the groupBy function to group the list of words based on their first character. The returned map has keys 'a', 'b', and 'c', corresponding to the first letters of the words, and the values are lists of words starting with each letter.
The groupBy function creates a grouping object internally that performs the grouping based on the lambda argument you provide. This grouping object then produces the result map by processing the original collection. The resulting map contains all the elements grouped by the key generated from the lambda expression.
You can customize the grouping criteria by providing a more complex lambda expression. For example, let's group a list of strings by their length:
1val words = listOf("cat", "dog", "elephant", "giraffe", "hippo", "ant") 2 3val groupedByLength = words.groupBy { it.length } 4println(groupedByLength)
Output:
1{3=[cat, dog, ant], 8=[elephant], 7=[giraffe], 5=[hippo]}
Here, the groupBy function groups the words based on their length. The keys in the returned map are the lengths of the words, and the values are lists of words that have the same length.
Kotlin's groupBy function also has a variant that takes a second lambda argument to transform the elements before adding them to the lists. This is useful when you want to modify the grouped values in some way.
1val words = listOf("apple", "banana", "apricot", "blueberry", "cherry") 2 3val groupedByFirstLetterAndUppercased = words.groupBy( 4 keySelector = { it.first() }, 5 valueTransform = { it.uppercase() } 6) 7println(groupedByFirstLetterAndUppercased)
Output:
1{a=[APPLE, APRICOT], b=[BANANA, BLUEBERRY], c=[CHERRY]}
In this example, the second lambda argument is used to transform each element to uppercase before grouping. The returned map still has the keys as the first character of each word, but the values are the uppercase versions of the words.
You can also use the groupBy function to group collections of custom objects. Let's create a data class representing a Person and group them by age:
1data class Person(val name: String, val age: Int) 2 3val people = listOf( 4 Person("Alice", 30), 5 Person("Bob", 25), 6 Person("Charlie", 30), 7 Person("David", 25), 8 Person("Edward", 35) 9) 10 11val groupedByAge = people.groupBy { it.age } 12println(groupedByAge)
Output:
1{30=[Person(name=Alice, age=30), Person(name=Charlie, age=30)], 25=[Person(name=Bob, age=25), Person(name=David, age=25)], 35=[Person(name=Edward, age=35)]}
Here, we group the list of Person instances by their age. The returned map has keys representing different ages and values containing the list of Person objects of that age.
Once you have a returned map from the groupBy function, you can perform various operations on the grouped data. For instance, you can count the number of elements in each group:
1val wordCountsByFirstLetter = words.groupBy { it.first() }.mapValues { it.value.count() } 2println(wordCountsByFirstLetter)
Output:
1{a=2, b=2, c=1}
Here, the mapValues function is used to transform the values in the returned map by counting the number of elements in each group.
You can also use the fold function to perform complex operations on the grouped elements. For example, let's sum the lengths of all the words in each group:
1val lengthSumByFirstLetter = words.groupBy { it.first() } 2 .mapValues { it.value.fold(0) { acc, word -> acc + word.length } } 3 4println(lengthSumByFirstLetter)
Output:
1{a=11, b=15, c=6}
Here, the fold function is used to accumulate the sum of the lengths of words in each group. The result map shows the sum of word lengths for each first letter.
In this article, we explored the power and flexibility of the Kotlin groupBy function for grouping elements in collections based on custom criteria. We covered its basic usage, customization options with lambda arguments, and advanced use cases, such as grouping custom objects and performing operations on grouped data.
The main takeaway is that Kotlin groupBy is a versatile and efficient way to manage collections by grouping them into meaningful categories using keys. By leveraging the groupBy function and its variants, you can simplify data processing and make your Kotlin code cleaner and more readable.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.