SlideShare a Scribd company logo
1 of 58
Kotlin Collections
Hello!
Android Engineer @LyrebirdStudio
I am here because I love share everything I know.
You can find me at @ozcandroid
2
I am Halil ÖZCAN
“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
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?
◎ 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
◎ 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
◎ 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
8
9
10
Let’s Play With
Lists
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
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
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!]
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
}
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
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]
18
val complexList =
listOf(null,"Kotlin",1967,null,true)
complexList.filterIsInstance<String>() // Kotlin
complexList.filterNotNull() // [Kotlin, 1967, true]
complexList.filterNot { it == null }
// [Kotlin, 1967, true]
19
Partitioning List
&
Sublisting
val kotlinLanguage = "Kotlin"
val languages = listOf("Kotlin", "Java", "C", "PHP",
"Javascript")
val(match,rest) = languages.partition {
it == kotlinLanguage
}
// match [Kotlin]
// rest [Java, C, PHP, Javascript]
val subLanguages = languages.subList(1,languages.size-1)
// [Java, C, PHP, Javascript]
21
Take & Drop
val eventWordList = listOf("Kotlin", "Everywhere", "is", "a",
"great", "event", "!")
eventWordList.take(4) // [Kotlin, Everywhere, is, a]
eventWordList.takeLast(5) // [is, a, great, event, !]
eventWordList.drop(1) // [Everywhere, is, a, great, event, !]
eventWordList.dropLast(5) // [Kotlin, Everywhere]
val eventWordList = listOf("Kotlin", "Everywhere", "is", "a",
"great", "event", "!")
eventWordList.takeWhile { !it.startsWith("a") }
// [Kotlin, Everywhere, is]
eventWordList.takeLastWhile { it != "Kotlin" }
// [Everywhere, is, a, great, event, !]
eventWordList.dropWhile { !it.startsWith("a") }
// [a, great, event, !]
eventWordList.dropLastWhile { !it.startsWith("E") }
// [Kotlin, Everywhere]
24
Chunked
val numbers = (1..10).toList()
numbers.chunked(3)
// [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
numbers.chunked(3){
it.sum()
}
// [6, 15, 24, 10]
26
Windowed
val numbers = (1..5).toList()
numbers.windowed(3)
// [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
numbers.windowed(3, step = 2, partialWindows = true)
// [[1, 2, 3], [3, 4, 5], [5]]
numbers.windowed(3) {
it.sum()
}
// [6, 9, 12]
28
Folds & Reduce
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!
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
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
32
Let’s Play With
Sets
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?]
val numberSet = listOf(
setOf(1, 2, 3), setOf(4, 5, 6), setOf(7, 8, 9))
numberSet.first().first() // 1
numberSet.first().last() // 3
numberSet.last().first() // 7
numberSet.last().last() // 9
val numbers = setOf(1, 2, 3, 4, 5)
numbers intersect setOf(1, 2)
// [1, 2]
numbers subtract setOf(4, 5)
// [1, 2, 3]
numbers subtract setOf(5, 4)
// [1, 2, 3]
36
Let’s Play With
Maps
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
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!")
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}
41
42
Sequences
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
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]
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
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
val eventWordList = "Kotlin Everywhere is a
great event".split(" ")
eventWordList.filter {
it.length > 5
}.map {
it.toUpperCase()
}.take(4)
// [KOTLIN, EVERYWHERE]
12 Steps 😒
val eventWordList = "Kotlin Everywhere is a great
event".split(" ")
val eventWordsSequence = eventWordList.asSequence()
eventWordsSequence.filter {
it.length > 5
}.map {
it.toUpperCase()
}.take(2)
// [KOTLIN, EVERYWHERE]
8 Steps 😉
51
Collection Transformations
52
Mapping
val cities = listOf("İstanbul", "Ankara", "Trabzon")
val citiesMap = mapOf(34 to "İstanbul", 6 to "Ankara", 61 to
"Trabzon")
cities.map { it.toUpperCase() }
// [İSTANBUL, ANKARA, TRABZON]
cities.mapIndexed { index, element ->
index + element.length
} // [8, 7, 9]
citiesMap.mapKeys { it.key * 2 }
//{68=İstanbul, 12=Ankara, 122=Trabzon}
citiesMap.mapValues { it.key + it.value.length }
//{34=42, 6=12, 61=68}
54
Zipping
val foundedYears = listOf(1975, 1976, 1998)
val companies = listOf("Microsoft", "Apple", "Google")
companies.zip(foundedYears) { company, foundedYear ->
"$company - $foundedYear"
}
// [Microsoft - 1975, Apple - 1976, Google - 1998]
val companyPairs = listOf(1975 to "Microsoft", 1976 to
"Apple", 1998 to "Google")
companyPairs.unzip()
//([1975, 1976, 1998], [Microsoft, Apple, Google])
56
Association
val names = listOf("Halil", "Murat", "Elif", "Okan")
println(names.associateWith {
it.length
})
// {Halil=5, Murat=5, Elif=4, Okan=4}
println(names.associateBy(keySelector = {
it.toLowerCase()
}, valueTransform = {
it.length
}))
// {Halil=5, Murat=5, Elif=4, Okan=4}
Thanks!
Any questions?
You can find me at @ozcandroid & mail@halilozcan.com
58

More Related Content

What's hot

Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in KotlinAlexey Soshin
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in javaTalha mahmood
 
Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIOJohn De Goes
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Atif AbbAsi
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Philip Schwarz
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23myrajendra
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentationManeesha Caldera
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 

What's hot (20)

Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 
Two-dimensional array in java
Two-dimensional array in javaTwo-dimensional array in java
Two-dimensional array in java
 
Error Management: Future vs ZIO
Error Management: Future vs ZIOError Management: Future vs ZIO
Error Management: Future vs ZIO
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Java collection
Java collectionJava collection
Java collection
 
Generics
GenericsGenerics
Generics
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentation
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 

Similar to Kotlin Collections Guide

Hello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebHello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebMuhammad Raza
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKirill Rozov
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfRahul04August
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageAnıl Sözeri
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Elixir: the not-so-hidden path to Erlang
Elixir: the not-so-hidden path to ErlangElixir: the not-so-hidden path to Erlang
Elixir: the not-so-hidden path to ErlangLaura M. Castro
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Codemotion
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 

Similar to Kotlin Collections Guide (20)

Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Hello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebHello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC Unideb
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platforms
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Elixir: the not-so-hidden path to Erlang
Elixir: the not-so-hidden path to ErlangElixir: the not-so-hidden path to Erlang
Elixir: the not-so-hidden path to Erlang
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 

Recently uploaded (20)

Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 

Kotlin Collections Guide

  • 2. Hello! Android Engineer @LyrebirdStudio I am here because I love share everything I know. You can find me at @ozcandroid 2 I am Halil ÖZCAN
  • 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
  • 8. 8
  • 9. 9
  • 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]
  • 18. 18 val complexList = listOf(null,"Kotlin",1967,null,true) complexList.filterIsInstance<String>() // Kotlin complexList.filterNotNull() // [Kotlin, 1967, true] complexList.filterNot { it == null } // [Kotlin, 1967, true]
  • 20. val kotlinLanguage = "Kotlin" val languages = listOf("Kotlin", "Java", "C", "PHP", "Javascript") val(match,rest) = languages.partition { it == kotlinLanguage } // match [Kotlin] // rest [Java, C, PHP, Javascript] val subLanguages = languages.subList(1,languages.size-1) // [Java, C, PHP, Javascript]
  • 22. val eventWordList = listOf("Kotlin", "Everywhere", "is", "a", "great", "event", "!") eventWordList.take(4) // [Kotlin, Everywhere, is, a] eventWordList.takeLast(5) // [is, a, great, event, !] eventWordList.drop(1) // [Everywhere, is, a, great, event, !] eventWordList.dropLast(5) // [Kotlin, Everywhere]
  • 23. val eventWordList = listOf("Kotlin", "Everywhere", "is", "a", "great", "event", "!") eventWordList.takeWhile { !it.startsWith("a") } // [Kotlin, Everywhere, is] eventWordList.takeLastWhile { it != "Kotlin" } // [Everywhere, is, a, great, event, !] eventWordList.dropWhile { !it.startsWith("a") } // [a, great, event, !] eventWordList.dropLastWhile { !it.startsWith("E") } // [Kotlin, Everywhere]
  • 25. val numbers = (1..10).toList() numbers.chunked(3) // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] numbers.chunked(3){ it.sum() } // [6, 15, 24, 10]
  • 27. val numbers = (1..5).toList() numbers.windowed(3) // [[1, 2, 3], [2, 3, 4], [3, 4, 5]] numbers.windowed(3, step = 2, partialWindows = true) // [[1, 2, 3], [3, 4, 5], [5]] numbers.windowed(3) { it.sum() } // [6, 9, 12]
  • 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?]
  • 34. val numberSet = listOf( setOf(1, 2, 3), setOf(4, 5, 6), setOf(7, 8, 9)) numberSet.first().first() // 1 numberSet.first().last() // 3 numberSet.last().first() // 7 numberSet.last().last() // 9
  • 35. val numbers = setOf(1, 2, 3, 4, 5) numbers intersect setOf(1, 2) // [1, 2] numbers subtract setOf(4, 5) // [1, 2, 3] numbers subtract setOf(5, 4) // [1, 2, 3]
  • 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}
  • 41. 41
  • 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]
  • 49. val eventWordList = "Kotlin Everywhere is a great event".split(" ") val eventWordsSequence = eventWordList.asSequence() eventWordsSequence.filter { it.length > 5 }.map { it.toUpperCase() }.take(2) // [KOTLIN, EVERYWHERE]
  • 53. val cities = listOf("İstanbul", "Ankara", "Trabzon") val citiesMap = mapOf(34 to "İstanbul", 6 to "Ankara", 61 to "Trabzon") cities.map { it.toUpperCase() } // [İSTANBUL, ANKARA, TRABZON] cities.mapIndexed { index, element -> index + element.length } // [8, 7, 9] citiesMap.mapKeys { it.key * 2 } //{68=İstanbul, 12=Ankara, 122=Trabzon} citiesMap.mapValues { it.key + it.value.length } //{34=42, 6=12, 61=68}
  • 55. val foundedYears = listOf(1975, 1976, 1998) val companies = listOf("Microsoft", "Apple", "Google") companies.zip(foundedYears) { company, foundedYear -> "$company - $foundedYear" } // [Microsoft - 1975, Apple - 1976, Google - 1998] val companyPairs = listOf(1975 to "Microsoft", 1976 to "Apple", 1998 to "Google") companyPairs.unzip() //([1975, 1976, 1998], [Microsoft, Apple, Google])
  • 57. val names = listOf("Halil", "Murat", "Elif", "Okan") println(names.associateWith { it.length }) // {Halil=5, Murat=5, Elif=4, Okan=4} println(names.associateBy(keySelector = { it.toLowerCase() }, valueTransform = { it.length })) // {Halil=5, Murat=5, Elif=4, Okan=4}
  • 58. Thanks! Any questions? You can find me at @ozcandroid & mail@halilozcan.com 58