Blog Infos
Author
Published
Topics
Published

Without wasting time let’s move on to understand what actually we want to discuss in this article. As title suggests ‘ Grouping ‘, what is grouping?

In programming, Grouping is used to group collections on the basis of certain characteristics. Let’s say we have a list of our upcoming tasks to perform in next week. We want to group tasks according to first character in their name.

In such cases ‘ Grouping ‘ helps a lot. We can group items based on length, type, object category etc.

Okay so let’s see how it’s done in Kotlin.

Using groupBy() Kotlin extension function. What happens when we use this function:

  1. It will return a ‘ map ‘ which contains keys and list of groups.
  2. Keys will be the lambda result and list of groups corresponding to keys will actually be those lists on which result is applied.
                                 Usage of groupBy()

3. As we can see in above program, result returned is actually a map with keys which is obtained from lambda argument with groupBy() and values is the lists on which argument result is applied.

Another thing we can do with groupBy() is passing another lambda argument also called as ‘ Value Transformation Function ‘. What does it do?

It transforms the actual values in collection and mapped with keys (obtained from the first lambda argument) into a result map.

       Usage of Value Transformation Function with groupBy()

Okay so it’s all about grouping a collection based on some criteria.

Now what if we want to perform an operation for all groups at once. I mean I want the count of tasks grouped according to first character of their name. As you can see I am asking to apply operation on all groups.

Simply we can think of iterating over resulted map but it adds lot of confusion and even after that it is not clear that we will be able to print first character with the number of items starting with that character.

So, in such cases Kotlin has provided us a groupingBy() function that allows us to apply operation for all groups at once and return a ‘Grouping’ object. I am again requesting you to focus on its return type. It will not return map, it will return a ‘ Grouping ‘ object. Let’s see it in action.

                        Usage of groupingBy() function

As we can see, eachCount() is used to perform operation on all groups. It will help to obtain the count of lambda argument. There are another operations we can perform as well. You can see the official documentation for the reference “ https://kotlinlang.org/docs/collection-grouping.html “

I will end this article by showing you difference between the return type of groupBy() & groupingBy(). Look below into the image, observe the difference between first and second output. First output is the count of type map and another is a grouping object. This is the main difference between groupBy() & groupingBy().

  First output is of groupBy() and second output is of groupingBy()

Job Offers

Job Offers


    Senior Compiler Engineer C++/LLVM – Munich

    Guardsquare
    Munich
    • Full Time
    apply now

    Developer (m/w/d) Backend/ Mobile

    Payback GmbH
    Cologne, Germany
    • Full Time
    apply now

    Android Engineer (m/f/x)

    Scalable Capital GmbH
    München, Berlin, remote
    • Full Time
    apply now
Load more listings

OUR VIDEO RECOMMENDATION

, , ,

Painless Persistence on Kotlin Multiplatform with Realm Kotlin

In this session, we will explore a fast, intuitive way to build great mobile applications using Realm’s new Kotlin SDK with Multiplatform support. We will dive deeper into how we evolved the Realm Java SDK to be a fully native Kotlin Multiplatform SDK. You will learn how Realm’s natural object model combined with Kotlin features like…
READ MORE

Jobs

So I hope you are now able to understand the basics of grouping of collection and how to perform operations on it.

PS : I got a good idea by one of the developer I follow on Twitter to include some complex examples to make readers understand the real world usage of Kotlin grouping.

So as he suggested me to take an example to group the ‘ Complete ‘ & ‘ Incomplete’ tasks in a Todo list.

Okay, so let’s understand how it can be done. It’s better idea to create a Data class for Task name & Status of task completion. It will be helpful in creating a list of objects of Data class. Now it’s easy to group.

Now we need to think what are the ways we can group. We have two ways :

  1. Simple grouping — It will group the list elements as per lambda argument. Since list elements are data class objects. So it will return Key as per lambda argument & value as data class object.
  2. Value transformation — In this case, second lambda argument will transform the data class object the way we require and append as value to the keys obtained by first lambda argument.

In this case we will use ‘ Value Transformation ‘ and insert two lambda argument so that we can only see the tasks name as per their completion status.

As we can see in above program we used two lambda arguments to get the neat and desired result. We used ‘ GroupingBy‘ as well to get the count of completed and incompleted tasks.

This example helped us to get to know about real world application of Grouping and how it can be used for various use cases.

So it’s all done about ‘ Kotlin Grouping ‘ and special mention to Matt M for asking me to include this example.

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
Nowadays authentication has become common in almost all apps. And many of us know…
READ MORE
blog
Collections are a set of interfaces and classes that implement highly optimised data structures.…
READ MORE
blog
Hi, today I come to you with a quick tip on how to update…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu