Home

Kotlin Arrays And Lists

Creating Arrays

Easiest way is to use the arrayOf func. Kotlin will infer the type.

val evenNumbers = arrayOf(2,4,6,8) // easy way to create an array with default values val fiveFives = arrayOf(5, {5}) // 5,5,5,5,5

Array Of Primitives

val oddNumbers = intArrayOf(1,3,5,7) val zeros = DoubleArray(4) // 0.0, 0.0, 0.0, 0.0 val otherOddNumbers = arrayOf(1,3,5,7).toIntArray()

Lists

List type in Kotlin is an interface that has concrete realizations in types such as ArrayList, LinkedList and others.

Lists have the additional features of being dynamically-sized.

val innerPlanets = listOf("Mercury", "Venus", "Earth", "Mars")

Empty Lists

val subscribers: List<String> = listOf() // same as val subscribers = listOf<String>()

Mutable Lists

val outerPlanets = mutableListOf("Jupiter", "Saturn", "Uranus", "Neptune") val exoPlanets = mutableListOf<String>()

List Properties and Methods

val players = mutableListOf("Alice", "Bob", "Cindy", "Dan") print(players.isEmpty()) // > false if (players.size < 2) { println("We need at least two players!") } else { println("Let's start!") } // > Let's start! var currentPlayer = players.first() println(currentPlayer) // > Alice println(players.last()) // > Dan val minPlayer = players.min() minPlayer.let { println("$minPlayer will start") // > Alice will start } println(arrayOf(2, 3, 1).first()) // > 2 println(arrayOf(2, 3, 1).min()) // > 1 val maxPlayer = players.max() if (maxPlayer != null) { println("$maxPlayer is the MAX") // > Dan is the MAX } val firstPlayer = players[0] println("First player is $firstPlayer") // > First player is Alice val secondPlayer = players.get(1) val upcomingPlayersSlice = players.slice(1..2) println(upcomingPlayersSlice.joinToString()) // > Bob, Cindy players.slice(1..3).contains("Alice") // false

Adding List Elements

players.add("Eli") // or players += "Gina" println(players.joinToString()) // > "Alice", "Bob", "Cindy", "Dan", "Eli", "Gina" // inserting elements players.add(5, "Frank")

Removing List Elements

val wasPlayerRemoved = players.remove("Gina") println("It is $wasPlayerRemoved that Gina was removed") // > It is true that Gina was removed val removedPlayer = players.removeAt(2) println("$removedPlayer was removed") // > Cindy was removed

Iterating Through A List

for (player in players) { println(player) } // > Alice // > Anna // > Bob // > Dan // > Franklin // with index for ((index, player) in players.withIndex()) { println("${index + 1}. $player") } // > 1. Alice // > 2. Anna // > 3. Bob // > 4. Dan // > 5. Franklin // if summing numbers fun sumOfElements(list: List<Int>): Int { var sum = 0 for (number in list) { sum += number } return sum }

Nullable Lists

You can have nullable lists, a list of nullables or both.

var nullableList = List<Int>? = listOf(1,2,3,4) // list can be nullable var listOfNullables = List<Int?> = listOf(1,2,null,4) // elements can be null

Maps and Sets

A map is an unordered collection of pairs, where each pair is compised of a a key and value.

Creating Maps

var yearOfBirth = mapOf("Anna" to 1990, "Brian" to 1991, "Craig" to 1992, "Donna" to 1993) var namesAndScores = mutableMapOf("Anna" to 2, "Brian" to 2, "Craig" to 8, "Donna" to 6) println(namesAndScores) // > {Anna=2, Brian=2, Craig=8, Donna=6} namesAndScores = mutableMapOf() var pairs = HashMap<String, Int>() pairs = HashMap<String, Int>(20)

Mutating Mutable Maps

val bobData = mutableMapOf( "name" to "Bob", "profession" to "CardPlayer", "country" to "USA") bobData.put("state", "CA") bobData["city"] = "San Francisco"

Updating Map Values

bobData.put("name", "Bobby") // Bob bobData["profession"] = "Mailman" val pair = "nickname" to "Bobby D" bobData += pair println(bobData) // > {name=Bobby, profession=Mailman, country=USA, state=CA, city=San Francisco, nickname=Bobby D}

Removing Pairs

bobData.remove("city") bobData.remove("state", "CA")

Iterating through maps

for ((player, score) in namesAndScores) { println ("$player - $score") } // > Anna - 2 // > Brian - 2 // > Craig - 8 // > Donna - 6 for (player in namesAndScores.keys) { print("$player, ") // no newline } println() // print a newline // > Anna, Brian, Craig, Donna,

Note: For performance-critical code, HashMap<K, V> should be used via hashMapOf() instead of mapOf().

Sets

A set is an unordered collection of unique values of the same type. This can be useful for uniqueness.

val names = setOf("Anna", "Brian", "Craig", "Anna") println(names) // > [Anna, Brian, Craig] // for an empty set val hashSet = HashSet<Int>()

Sets from Arrays

val someArray = arrayOf(1, 2, 3, 1) var someSet = mutableSetOf(*someArray) println(someSet) // > [1, 2, 3] println(someSet.contains(1)) // > true println(4 in someSet) // > false

Adding Or Removing Elements

someSet.add(5) val removedOne = someSet.remove(1) println(removedOne) // > true println(someSet) // > [2, 3, 5]

Repository

https://github.com/okeeffed/developer-notes-nextjs/content/kotlin/kotlin-arrays-and-lists

Sections


Related