Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Functional Kotlin

You're reading from   Functional Kotlin Extend your OOP skills and implement Functional techniques in Kotlin and Arrow

Arrow left icon
Product type Paperback
Published in Feb 2018
Publisher Packt
ISBN-13 9781788476485
Length 350 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Mario Arias Mario Arias
Author Profile Icon Mario Arias
Mario Arias
Rivu Chakraborty Rivu Chakraborty
Author Profile Icon Rivu Chakraborty
Rivu Chakraborty
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Kotlin – Data Types, Objects, and Classes FREE CHAPTER 2. Getting Started with Functional Programming 3. Immutability - It's Important 4. Functions, Function Types, and Side Effects 5. More on Functions 6. Delegates in Kotlin 7. Asynchronous Programming with Coroutines 8. Collections and Data Operations in Kotlin 9. Functional Programming and Reactive Programming 10. Functors, Applicatives, and Monads 11. Working with Streams in Kotlin 12. Getting Started with Arrow 13. Arrow Types 14. Kotlin's Quick Start 15. Other Books You May Enjoy

Grouping collections


Kotlin's collection framework allows you to group collections based on your requirements. For example, if you have a list of strings and want to group them with respect to their size, you can easily do that with the help of the groupBy function, which groups a collection based on the logic provided and returns Map with that group of collections.

So, the following is a short example:

fun main(args: Array<String>) { 
    val list = 1.rangeTo(50).toList() 
 
    println(list.groupBy { it%5 }) 
} 

So, what we did here is as follows: we created a list of Int containing numbers from 1 to 50 (both inclusive) then, we tried to group them based on their remnants when divided by 5.

So, there should be five groups, from 0 to 5, and each of them should contain 10 numbers. Let's check the following output to see if that happened or not:

So, the groupBy function just worked as expected and returned Map<Int,List<Int>> that contained the grouped list.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $24.99/month. Cancel anytime