Kotlin: Collection Processing Cheat Sheet

students
    .filter { it.passing && it.averageGrade > 4.0 }
    // Only passing students
    .sortedByDescending { it.averageGrade }
    // Starting from ones with biggest grades
    .take(10) // Take rst 10
    .sortedWith(compareBy({ it.surname }, { it.name }))
    // Sort by surname and then name
generateSequence(0) { it + 1 }
    // Innitive sequence of next numbers starting on 0
    .lter { it % 2 == 0 } // Keep only even
    .map { it * 3 } // Triple every one
    .take(100) // Take rst 100
    .average() // Count average

Most important functions for collection processing

val l = listOf(1,2,3,4)

filter – returns only elements matched by predicate

l.filter { it % 2 == 0 } // [2, 4]

map – returns elements after transformation

l.map { it * 2 } // [2, 4, 6, 8]

flatMap – returns elements yielded from results of trans.

l.flatMap { listOf(it, it + 10) } // [1, 11, 2, 12, 3, 13, 4, 14]

fold/reduce – accumulates elements

l.fold(0.0) { acc, i -> acc + i } // 10.0
l.reduce { acc, i -> acc * i } // 24

forEach/onEach – perfons an action on every element

l.forEach { print(it) } // Prints 1234, returns Unit
l.onEach { print(it) } // Prints 1234, returns [1, 2, 3, 4]

partition – splits into pair of lists

val (even, odd) = l.partition { it % 2 == 0 }
print(even) // [2, 4]
print(odd) // [1, 3]

min/max/minBy/maxBy

l.min() // 1, possible because we can compare Int
l.minBy { -it } // 4
l.max() // 4, possible because we can compare Int
l.maxBy { -it } // 1

first/firstBy

l.first() // 1
l.first { it % 2 == 0 } // 2 (rst even number)

count – count elements matched by predicate

l.count { it % 2 == 0 } // 2

sorted/sortedBy – returns sorted collection

listOf(2,3,1,4).sorted() // [1, 2, 3, 4]
l.sortedBy { it % 2 } // [2, 4, 1, 3]

groupBy – group elements on collection by key

l.groupBy { it % 2 } // Map: {1=[1, 3], 0=[2, 4]}

distinct/distinctBy – returns only unique elements

listOf(1,1,2,2).distinct() // [1, 2]

Mutable vs immutable collection processing functions

val list = mutableListOf(3,4,2,1)
val sortedResult = list.sorted() // Returns sorted
println(sortedResult) // [1, 2, 3, 4]
println(list) // [3, 4, 2, 1]
val sortResult = list.sort() // Sorts mutable collection
println(sortResult) // kotlin.Unit
println(list) // [1, 2, 3, 4]

Leave a Reply

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