The document provides an overview of Kotlin collections including lists, sets, and maps. It discusses collection interfaces like List, Set, and Map and their characteristics. The document then demonstrates various operations that can be performed on collections like filtering, mapping, partitioning, zipping, associating, and more through examples. It also compares the differences between iterables and sequences in Kotlin.
3. “I will, in fact, claim that the difference
between a bad programmer and a good
one is whether he considers his code or
his data structures more important.
Bad programmers worry about the
code.
Good programmers worry about data
structures and their relationships.”
3
4. “
4
A collection is a structure which
usually contains numbers of objects
(this number may be zero) that of
the same type. Objects in a
collection called element or items.
What are Collections?
5. ◎ A read-only interface that
provides operations for
accessing collection elements.
◎ A mutable interface that
extends the corresponding
read-only interface with write
operations : removing, adding,
updating... 5
Collection Type Interfaces
6. ◎ List: ordered collection with access
to elements by indices. Elements
can occur more than once. (Group
of words)
◎ Set: collection of unique elements
(a group of objects without
repetitions). (Alphabet)
6
Collection Types
7. ◎ Map: set of key value pair. Keys are
unique and each of them points to
exactly one value. Use for storing
logical connection. Students’ ID
and their class.
7
Collection Types
11. 11
val kotlinLanguage = "Kotlin"
val eventWordList =
listOf("Kotlin","Everywhere","is","a","great","event")
eventWordList.get(0) // Not Recommended
eventWordList[0] // getting element with index
eventWordList.indexOf(kotlinLanguage) // getting index of
element
eventWordList.shuffled() // Doesn't effect original collection
12. 12
val kotlinLanguage = "Kotlin"
val eventWordList =
mutableListOf("Kotlin","Everywhere","is","a","great",
"event")
eventWordList.set(0,"Java :(") // Not Recommended :)
eventWordList[0] = kotlinLanguage // Updating with index
eventWordList.removeAt(0) // Deleting with index
13. val exclamationMark = "!"
val eventWordList =
listOf("Kotlin","Everywhere","is","a","great","event","!")
val removedWithElement = eventWordList - exclamationMark // remove first
occurrence
// [Kotlin, Everywhere, is, a, great, event]
val removedWithList = eventWordList - listOf("is","a") // remove all
occurrences
// [Kotlin, Everywhere, great, event, !]
val addedList = eventWordList + "Let's fun with it!"
// [Kotlin, Everywhere, is, a, great, event, !, Let's fun with it!]
14. val names = listOf("Halil", "Murat", "Elif", "Okan")
names.first() // Halil
names.last() // Okan
names.elementAt(2) // Elif
names.elementAtOrNull(4) // prevent
IndexOutOfBoundException - returns null
names.elementAtOrElse(4) {
// Do something because of index not found
}
15. val names = listOf("Halil", "Murat","Kağan", "Elif", "Okan")
names.first {
it.contains("t")
} // Murat
names.last {
it.contains("f")
} // Elif
names.firstOrNull { // You can use also find() alias
it.startsWith("z")
} // Null
names.lastOrNull { //You can use also findLast() alias
it.endsWith("n")
} // Okan
16.
17. val languages = listOf("Kotlin", "Java", "C", "PHP",
"Javascript")
languages.filter { // Doesn't effect original collection
it.length > 4
}.forEach {
println(it)
}
val filteredLanguages = mutableListOf<String>()
languages.filterTo(filteredLanguages) {
it.length > 4
}
languages.filterIndexedTo(filteredLanguages){ index, _ ->
index == 3
} // filteredLanguages [Kotlin, Javascript, PHP]
29. val eventWordList = listOf("Kotlin ", "Everywhere ", "is ", "a
", "great ", "event", "!")
eventWordList.reduce { sentence, element ->
sentence + element
}
// Kotlin Everywhere is a great event!
eventWordList.fold("") { sentence, element ->
sentence + element
}
// Kotlin Everywhere is a great event!
30. any()
returns true if at
least one element
matches the
given predicate.
none()
returns true if
none of the
elements match
the given
predicate.
all()
returns true if all
elements match
the given
predicate. Note
that all()
returns true when
called with any
valid predicate on
an empty
collection
30
Testing Predicates
31. val eventSuccessWord = "great"
val eventFailWord = "bad"
val eventWordList =
listOf("Kotlin","Everywhere","is","a","great","event")
eventWordList.any { it == eventSuccessWord } // Event is
success
eventWordList.none { it == eventFailWord } // Event is success
eventWordList.all { it != eventFailWord} // Event is success
emptyList<String>().all { it.length>5 } // True
33. var tvSeries = mutableSetOf("Breaking Bad","How I Met Your
Mother?","Lost")
tvSeries = (tvSeries union setOf("Game Of
Thrones","Lost")).toMutableSet()
// Lost is not added again
// [Breaking Bad, How I Met Your Mother?, Lost, Game Of
Thrones]
val badFinals = mutableSetOf("Game Of Thrones","Lost")
tvSeries = (tvSeries - badFinals) as MutableSet<String>
// [Breaking Bad, How I Met Your Mother?]
37. val cityMap = mapOf(34 to "İstanbul",
6 to "Ankara", 61 to "Trabzon")
cityMap.get(34)
// get with function - Not Recommended
cityMap[34] // get with index
cityMap.keys // get all keys
cityMap.values // get all values
38. val cityMap = mutableMapOf(34 to "İstanbul", 6 to "Ankara", 61 to
"Trabzon")
cityMap.put(16, "Bursa") // put with function - not recommended
cityMap[35] = "İzmir" // put-update with index
cityMap.remove(34) // delete
cityMap.getOrPut(28,{
"Giresun"
})
// if there is a value with key 28, get it otherwise put the value
with key 28
// {6=Ankara, 61=Trabzon, 16=Bursa, 35=İzmir, 28=Giresun}
cityMap.getOrDefault(34,"Not Found!")
39.
40. val cityMap = mutableMapOf(34 to "İstanbul", 6 to "Ankara", 61 to "Trabzon")
// Also there are filterKeys and filterValues functions
println(cityMap.filter { (key, value) ->
key >= 34 && value.length > 5
})
// {34=İstanbul, 61=Trabzon}
cityMap + Pair(16, "Bursa") // {34=İstanbul, 6=Ankara, 61=Trabzon, 16=Bursa}
cityMap + mapOf(28 to "Giresun") // {34=İstanbul, 6=Ankara, 61=Trabzon,
28=Giresun}
cityMap - listOf(61) // {34=İstanbul, 6=Ankara}
43. val sequence = sequenceOf(1, 2, 3, 4)
// You can use all iterable functions with sequences
listOf(1, 2, 3, 4).asSequence() // from iterable collection
generateSequence(1) {
it + 1
} // infinite sequence
generateSequence(1) {
if (it < 10) it else null
} // finite sequence
44. val evenNumbers = sequence {
// suspend until next element requested by consumer
yield(0) // return element to sequence consumer
yieldAll(listOf(2, 4)) // can take any Iterable or Sequence
yieldAll(generateSequence(6) {
it + 2
})
// infinite call
// - it must be last -
// all subsequent calls will never be executed
}
evenNumbers.take(5).toList()
// [0, 2, 4, 6, 8]
45. Iterable vs Sequences
● Sequences offer the
same functions as
Iterable but implement
another approach to
multi-step collection
processing.
● When the processing of an
Iterable each process step
completes and returns its
result – an intermediate
collection. In turn, multi-
step processing of
sequences is executed lazily
when possible
45
46. Iterable vs Sequences
● The order of operations execution is different
as well: Sequence performs all the processing
steps one-by-one for every single element. In
turn, Iterable completes each step for the whole
collection and then proceeds to the next step.
46
47. val eventWordList = "Kotlin Everywhere is a
great event".split(" ")
eventWordList.filter {
it.length > 5
}.map {
it.toUpperCase()
}.take(4)
// [KOTLIN, EVERYWHERE]