Xantier - Kotlin Collection Extensions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Kotlin Collection Extensions Cheat Sheet

by Xantier via cheatography.com/38756/cs/12075/

Creating Collec​tions

Arrays

Simple Array val intArray: Array<​Int> = arrayOf(1, 2, 3)

Copy of Array val copyOf​Array: Array<​Int> = intArr​ay.c​op​yOf()

Partial copy of val partia​lCo​pyO​fArray: Array<​Int> = intArr​ay.c​op​yOf​Ran​ge(0, 2)


Array

Lists

Simple List val intList: List<I​nt> = listOf(1, 2, 3) Or array​Lis​tOf​(1,​2,3)

Empty List val emptyList: List<I​nt> = emptyL​ist() Or listOf()

List with no null val listWi​thN​onN​ull​Ele​ments: List<I​nt> = same as List(​1,3)


elements listOf​Not​Null(1, null, 3)

Sets

Simple Set val aSet: Set<In​t> = setOf(1) Or hashS​etO​f(1) / linke​dSe​rOf(1)

Empty Set val emptySet: Set<In​t> = emptyS​et() Or setOf() / hashS​etOf() / linke​dSe​tOf()

Maps

Simple Map val aMap: Map<St​ring, Int> = mapOf(​"​hi" to 1, Or mapOf​(Pa​ir(​"​hi", 1) / hashM​apO​f("h​i" to 1) /


"​hel​lo" to 2) linke​dMa​pOf​("hi​" to 1)

Empty Map val emptyMap: Map<St​ring, Int> = emptyM​ap() Or mapOf() / hashM​apOf() / linke​dMa​pOf()

Black sheep, mutables

Simple Mutable val mutabl​eList: Mutabl​eLi​st<​Int> = mutabl​eLi​stOf(1, 2, 3)


List

Simple Mutable val mutabl​eSet: Mutabl​eSe​t<I​nt> = mutabl​eSe​tOf(1)


Set

Simple Mutable var mutabl​eMap: Mutabl​eMa​p<S​tring, Int> = mutabl​eMa​pOf​("hi​" to 1, "​hel​lo" to 2)


Map

We will be using these collec​tions throughout the cheat sheet.

Operators

Method Exam​ple Result Expl​ana​tion

Itera​bles

Plus intList + 1 [1, 2, 3, 1] Returns a new iterables with old values + added one

Plus (Iterable) intList + listOf(1, 2, 3) [1, 2, 3, 1, 2, 3] Return a new iterables with old values + values from added iterable

Minus intList - 1 [2, 3] Returns a new iterables with old values - subtracted one

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 1 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Operators (cont)

Minus (Iterable) intList - listOf(1, 2) `[3] Returns a new iterables with old values - values from
subtracted iterable

Maps

Plus aMap + Pair("H​i", 2) {hi=1, hello=2, Returns new map with old map values + new Pair. Updates
Goodby​e=3} value if it differs

Plus (Map) aMap + mapOf(​Pai​r("h​ell​o", 2), {hi=1, hello=2, Returns new map with old map values + Pairs from added
Pair("G​ood​bye​", 3) Goodby​e=3} map. Updates values if they differ.

Minus aMap - Pair("H​i", 2) {Hi=2} Takes in a key and removes if found

Minus (Map) aMap - listOf​("he​llo​", "​hi") {} Takes in an iterable of keys and removes if found

Mutables

Minus Assign mutab​leList -= 2 [1, 3] Mutates the list, removes element if found. Returns boolean

Plus Assign mutab​leList += 2 [1, 3, 2] Mutates the list, adds element. Returns boolean

Minus Assign mutab​leM​ap.m​in​usA​ssi​gn(​"​hel​lo") {hi=1} Takes in key and removes if that is found from the mutated
(Mutab​leMap) map. Returns boolean. Same as -=

Plus Assign mutab​leM​ap.p​lu​sAs​sig​n("G​ood​bye​" {hi=1, Goodbye=3} Takes in key and adds a new pair into the mutated map.
(Mutab​leMap) to 3) Returns boolean. Same as +=

Transf​ormers

Method Exam​ple Result Expl​ana​tion

Associate intLi​st.a​ss​ociate { {1=1, 2=2, Returns a Map containing key-value pairs created by lambda
Pair(i​t.t​oSt​ring(), it) } 3=3}

Map intLi​st.map { it + 1 } [2,3,4] Returns a new list by transf​orming all elements from the initial
Iterable.

MapNotNull intLi​st.m​ap​NotNull { null } [] Returned list contains only elements that return as not null from
the lamdba

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 2 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Transf​ormers (cont)

MapIndexed intLi​st.m​ap​Indexed { idx, [2,4,5] Returns a new list by transf​orming all elements from the initial Iterable.
value -> Lambda receives an index as first value, element itself as second.

if (idx == 0) value + 1
else value + 2 }

MapInd​exe​d intLi​st.m​ap​Ind​exe​dNo​tNull [4,5] Combin​ation of Map, MapIndexed & MapInd​exe​dNo​tNull


No​tNull { idx, value ->
if (idx == 0) null
else value + 2 }

MapKeys aMap.m​apKeys { pair -> {hi, mate=1, Transforms all elements from a map. Receives a Pair to lambda, lamdba
pair.key + ", mate" } hello, mate=2} return value is the new key of original value

MapValues aMap.m​ap​Values { pair -> {hi=3, hello=4} Transforms all elements from a map. Receives a Pair to lambda, lamdba
pair.value + 2 }) return value is the new value for the original key.

Reversed intLi​st.r​ev​ers​ed()) [3,2,1]

Partition intLi​st.p​ar​tition { it > Pair(​[1,2], Splits collection into to based on predicate


2 }) [3])

Slice intLi​st.s​li​ce(​1..2)) [2,3] Takes a range from collection based on indexes

Sorted intLi​st.s​or​ted()) [1,2,3]

Sorted​ByD​e intLi​st.s​or​ted​ByD​esc​endin [3,2,1] Sorts descending based on what lambda returns. Lamdba receives the value
sc​ending g { it } itself.

SortedWith intLi​st.s​or​ted​Wit​h(C​omp​ar [3,1,2] Takes in a Comparator and uses that to sort elements in Iterable.
a​tor​<In​t> { x, y ->
when {
x == 2 -> 1
y == 2 -> -1
else -> y - x
}
})

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 3 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Transf​ormers (cont)

Flatten listO​f(i​ntList, [2,3,​4,1] Takes elements of all passed in collec​tions and returns a collection with all
aSet).f​la​tten() those elements

FlatMap listO​f(i​ntList, [2,3,​4,1] Used for Iterable of Iterables and Lambdas that return Iterables. Transforms
with just aSet).f​latMap { it } elements and flattens them after transf​orm​ation.
return

FlatMap listOf​(in​tList, [2,3,​4,2] FlatMap is often used with monadic containers to fluently handle context, errors
with aSet).f​latMap { iterable: and side effects.
transform
Iterab​le<​Int> ->
iterable.map { it + 1 }
}

Zip listOf(3, 4).zip​(in​tList) [(3,1), Creates a list of Pairs from two Iterables. As many pairs as values in shorter of
(4,2)] the original Iterables.

Zip with listOf(3, 4).zip​(in​tList) { [(1,3), Creates a list of Pairs from two Iterables. As many pairs as values in shorter of
predicate firstElem, secondElem -> (2,4)] the original Iterables. Lambda receives both items on that index from Iterables.

Pair(firstElem - 2,
secondElem + 2)
}

Unzip listO​f(P​air​("hi​", 1), Pair([hi, Reverses the operation from zip. Takes in an Iterable of Pairs and returns them
Pair("h​ell​o", 2)).un​zip() hello], as a Pair of Lists.
[1,2])

Aggreg​ators

Method Exam​ple Result Expl​ana​tion

Folds And Reduces

Fold intLi​st.f​ol​d(10) { accumu​lator, 16 Accumu​lates values starting with initial and applying operation from left to right.
value -> (10+1​+2 Lambda receives accumu​lated value and current value.

accumu​lator + value } +3)

FoldIn​d intLi​st.f​ol​dIn​dex​ed(10) { idx, 13 Accumu​lates values starting with initial and applying operation from left to right.
exed accumu​lator, value -> (10+1+2) Lambda receives index as the first value.

if (idx == 2) accumu​lator else


accumu​lator + value }

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 4 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Aggreg​ators (cont)

FoldRight intLi​st.f​ol​dRi​ght(10) { 16 Accumu​lates values starting with initial and applying operation from right to left.
accumu​lator, value -> (10+3​+2 Lambda receives accumu​lated value and current value.

accumu​lator + value } +1)

FoldRi​ght​In intLi​st.f​ol​dRi​ght​Ind​exe​d(10) { 16 (10+3​+2+1)


dexed idx, accumu​lator, value ->
if (idx == 2) accumu​lator else
accumu​lator + value }

Reduce intLi​st.r​educe { accumu​lator, 6 Accumu​lates values starting with first value and applying operation from left to
value -> (1+2+3) right. Lambda receives accumu​lated value and current value.

accumu​lator + value }

Reduce​Rig intLi​st.r​ed​uce​Right { 6 Accumu​lates values starting with first value and applying operation from right to
ht accumu​lator, value -> (3+2+1) left. Lambda receives accumu​lated value and current value.

accumu​lator + value }

Reduce​Inde intLi​st.r​ed​uce​Indexed { idx, 3 (1+2)


xed accumu​lator, value ->
if (idx == 2) accumu​lator else
accumu​lator + value }

Reduce​Rig​ intLi​st.r​ed​uce​Rig​htI​ndexed { idx, 3 (2+1)


htI​ndexed accumu​lator, value ->
if (idx == 2) accumu​lator else
accumu​lator + value }

Grouping

GroupBy intLi​st.g​roupBy { value -> 2 } {2=[1, Uses value returned from lamdba to group elements of the Iterable. All values
2, 3]} whose lambda returns same key will be grouped.

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 5 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Aggreg​ators (cont)

GroupBy intLi​st.g​ro​upBy({ it }, { it + 1 }) {1= Same as group by plus takes another lambda that
(With new [2], can be used to transform the current value
values)
2=
[3],
3=
[4]}

GroupByTo val mutabl​eSt​rin​gTo​ListMap = mapOf(​"​fir​st" to 1, {1= Group by first lambda, modify value with second
"​sec​ond​" to 2) [11], lambda, dump the values to given mutable map
2=
mutableStringToListMap.values.groupByTo(mutableMapOf<Int,
[12]}
Mutabl​eLi​st<​Int​>>(), { value: Int -> value }, { value ->
value + 10 })

GroupingBy intLi​st.g​ro​upingBy { it } {1=1, Create a grouping by a lambda, fold using passed


-> FoldTo .foldTo(mutableMapOf<Int, Int>(), 0) { accumu​lator, 2=2, in lambda and given initial value, insert into given

element -> 3=3} mutable destin​ation object

accumu​lator + element }

Grouping > intLi​st.g​ro​upingBy { "​key​" } {key Create a grouping by a lambda, aggregate each
Aggregate .aggregate({ key, accumu​lator: String?, element, isFirst =​123} group. Lambda receives all keys, nullable
accumu​lator and the element plus a flag if value is
->
the first on from this group. If isFirst -->
​ when (accum​ulator) {
accumu​lator is null.
​ ​ ​ null -> "​$el​eme​nt"
​ ​ ​ else -> accumu​lator + "​$el​eme​nt"
​ }
})

Aggregating

Count intLi​st.c​ou​nt() 3 AKA size

Count (with intLi​st.c​ount { it == 2 }) 1 Count of elements satisfying the predicate


Lambda)

Average intLi​st.a​ve​rage() 2.0 Only for numeric Iterables


((1+2​+
3)/3 =
2.0)

Max intLi​st.m​ax() 3 Maximum value in the list. Only for Iterables of


Compar​ables.

MaxBy intLi​st.m​axBy { it * 3 } 3 Maximum value returned from lambda. Only for


Lambdas returning Compar​ables.

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 6 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Aggreg​ators (cont)

MaxWith intLi​st.m​ax​Wit​h(o​neO​rLa​rger) 1 Maximum value defined by passed in Comparator

Min intLi​st.m​in() 1 Minimum value in the list. Only for Iterables of Compar​ables.

MinBy intLi​st.m​inBy { it * 3 } 1 Minimum value returned from lambda. Only for Lambdas returning
Compar​ables.

MinWith intLi​st.m​in​Wit​h(o​neO​rLa​rger) 3 Minimum value defined by passed in Comparator

Sum intLi​st.s​um() 6 Summation of all values in Iterable. Only numeric Iterables.

SumBy intLi​st.s​umBy { if(it == 3) 6 else 9 Summation of values returned by passed in lambda. Only for lambdas returning
it }) (1+2+6) numeric values.

SumByD​ou intLi​st.s​um​ByD​ouble { 6.0 Summation to Double values. Lambda​rec​eives the value and returns a Double.
ble it.toD​ouble() }

val oneOrL​arger = Compar​ato​r<I​nt> { x, y ->


​ when{
​ ​ ​ x == 1 -> 1
​ ​ ​ y == 1 -> -1
​ ​ ​ else -> y - x
​ }
}

Filtering and other predicates + simple HOFs

Method Exam​ple Result Notes

Filtering

Filter intLi​st.f​ilter { it > 2 } [3] Filter-in

FilterKeys aMap.f​il​terKeys { it != "​hel​lo" } {hi=1}

Filter​Value aMap.f​il​ter​Values { it == 2 } {hell​o=2}


s

Filter​Index intLi​st.f​il​ter​Indexed { idx, value -> idx == 2 [2,3]


ed || value == 2 }

Filter​IsI​nst intLi​st.f​il​ter​IsI​nst​anc​e<S​tri​ng>() [] All of them are ints


ance

Taking and Dropping

Take intLi​st.t​ak​e(2) [1,2] Take n elements from Iterable. If passed in number larger than
list, full list is returned.

TakeWhile intLi​st.t​ak​eWhile { it < 3 } [1,2]

TakeLast intLi​st.t​ak​eLa​st(2) [2,3]

TakeLa​stW intLi​st.t​ak​eLa​stWhile { it < 3 } [] Last element already satisfies this condition --> empty
hile

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 7 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Filtering and other predicates + simple HOFs (cont)

Drop intLi​st.d​ro​p(2) [3] Drop n elements from the start of the Iterable.

DropWhile intLi​st.d​ro​pWhile { it [3]


< 3 }

DropLast intLi​st.d​ro​pLa​st(2) [1]

DropLa​stWhile intLi​st.d​ro​pLa​stWhile { [1, 2]


it > 2 }

Retrieving individual elements

Component intLi​st.c​om​pon​ent1() 1 There are 5 of these --> compo​nen​t1(), compo​nen​t2(), compo​nen​t3(),


compo​nen​t4(), compo​nen​t5()

ElementAt intLi​st.e​le​men​tAt(2) 3 Retrieve element at his index. Throws IndexO​utO​fBounds if element index doesn't
exist

Elemen​tAt​OrElse intLi​st.e​le​men​tAt​OrE​lse( 4 Retrieve element at his index or return lambda value if element index doesn't exist.
13) { 4 }

Elemen​tAt​OrNull intLi​st.e​le​men​tAt​OrN​ull​( null Retrieve element at his index or return null if element index doesn't exist.
666)

Get (clumsy syntax) intLi​st.g​et(2) 3 Get element by index

Get intLi​st[2] 3 Shorthand and preferred way for the one above

GetOrElse intLis​t.g​etO​rEl​se(14) { 42 } 42 Get element or return lambda value if it doesn't exist.

Get from Map aMap.g​et​("hi​") 1


(clumsy syntax)

Get from Map aMap[​"​hi"] 1

GetValue `aMap.g​et​Val​ue(​"​hi")1 1 Get value or throw NoSuch​Ele​men​tEx​ception

GetOrD​efault aMap.g​et​OrD​efa​ult​("HI​", 4 Get value or return the value returned from lambda
4)

GetOrPut mutab​leM​ap.g​et​OrP​ut(​"​HI" 5 MutableMap only. Returns the the value if it exist, otherwise puts it and returns put
) { 5 } value.

Finding

Binary​Search intLi​st.b​in​ary​Sea​rch(2) 1 Does a binary search through the collection and returns the index of the element if
found. Otherwise returns negative index.

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 8 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Filtering and other predicates + simple HOFs (cont)

Find intLi​st.find { it > 1 } 2 First element satisfying the condition or null if not found

FindLast intLi​st.f​in​dLast { it > 1 } 3 Last element satisfying the condition or null if not found

First intLi​st.f​ir​st() 1 First element of Iterable or throws


NoSuch​Ele​men​tEx​ception

First with predicate intLi​st.f​irst { it > 1 } 2 Same as find but throws NoSuch​Ele​men​tEx​ception if not
found

FirstO​rNull intLi​st.f​ir​stO​rNu​ll() 1 Throw safe version of first().

FirstO​rNull with intLi​st.f​ir​stO​rNull { it > 1 } 2 Throw safe version of first(() -> Boolean).
predicate

IndexOf intLi​st.i​nd​exO​f(1) 0

IndexO​fFirst intLi​st.i​nd​exO​fFirst { it > 1 } 1

IndexO​fLast intLi​st.i​nd​exO​fLast { it > 1 } 2

Last intLi​st.l​ast() 3 Throws NoSuch​Ele​men​tEx​ception if empty Iterable

Last with predicate intLi​st.last { it > 1 } 3 Throws NoSuch​Ele​men​tEx​ception if none found satisfying
the condition.

LastIn​dexOf intLi​st.l​as​tIn​dex​Of(2) 1

LastOrNull intLi​st.l​as​tOr​Null() 3 Throw safe version of last()

LastOrNull with intLi​st.l​as​tOrNull { it > 1 } 3 Throw safe version of last(() -> Boolean) .
predicate

Unions, distincts, inters​ections etc.

Distinct intLi​st.d​is​tin​ct() [1, 2, 3]

DistinctBy intLi​st.d​is​tinctBy { if (it > 1) it [1,3]


else 2 }

Intersect intLi​st.i​nt​ers​ect​(li​stOf(1, 2)) [1,2]

MinusE​lement intLi​st.m​in​usE​lem​ent(2) [1,3]

MinusE​lement with intLi​st.m​in​usE​lem​ent​(li​stOf(1, 2)) [3]


collection

Single listO​f("One Elemen​t").s​in​gle() One Returns only element or throws.


Element

Single​OrNull intLi​st.s​in​gle​OrN​ull() null Throw safe version of singl​e().

OrEmpty intLi​st.o​rE​mpty() [1, 2[, 3] Returns itself or an empty list if itself is null.

Union intLi​st.u​ni​on(​lis​tOf​(4,​5,6)) [1,2,​3,4​,5,6]

Union (infix notation) intList union listOf​(4,​5,6) [1,2,​3,4​,5,6]

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 9 of 10. http://crosswordcheats.com
Kotlin Collection Extensions Cheat Sheet
by Xantier via cheatography.com/38756/cs/12075/

Checks and Actions

Method Exam​ple Result Notes

Acting on list elements

val listOf​Fun​ctions = listOf({ print(​"​first ") }, { print(​"​second ") })

ForEach listO​fFu​nct​ion​s.f​orEach { it() } first second

ForEac​hIn​dexed listO​fFu​nct​ion​s.f​orE​ach​Indexed { idx, fn -> if (idx == 0) fn() else first Won't do it


print(​"​Won't do it") }

OnEach intLi​st.o​nEach { print(it) } 123

Checks

All intLi​st.all { it < 4 } true All of them are less


than 4

Any intLi​st.a​ny() true Collection has


elements

Any with intLi​st.any { it > 4 } false None of them are more


predicate than 4

Contains intLi​st.c​on​tai​ns(3) true

Contai​nsAll intLi​st.c​on​tai​nsA​ll(​lis​tOf(2, 3, 4)) false

Contains (Map) aMap.c​on​tai​ns(​"​Hel​lo") false Same as


conta​ins​Key()

Contai​nsKey aMap.c​on​tai​nsK​ey(​"​hel​lo") true Same as


conta​ins()

Contai​nsValue aMap.c​on​tai​nsV​alu​e(2) true

None intLi​st.n​one() false There are elements on


the list

None with intLi​st.none { it > 5 } true None of them are


predicate larger than 5

IsEmpty intLi​st.i​sE​mpty() false

IsNotEmpty intLi​st.i​sN​otE​mpty() true

<3 Kotlin

Github repository with all code examples:


https://github.com/Xantier/Kollections

PDF of this cheat sheet:


http://jussi.hallila.com/Kollections/

Created with <3 by Jussi Hallila

By Xantier Published 14th June, 2017. Sponsored by CrosswordCheats.com


cheatography.com/xantier/ Last updated 14th June, 2017. Learn to solve cryptic crosswords!
Page 10 of 10. http://crosswordcheats.com

You might also like