- Published on
Data Structures with Kotlin: Essential Skills
- Authors
- Name
- Dan Tech
- @dan_0xff
Kotlin provides developers with a complete set of data structures needed for a program. Let's explore these data structure types together.
Array, String
Array and String are common data structure types in Kotlin program logic. We often use them to store Text, Number, or Object data.
Refer to the example code below for how to use Array:
fun main() {
// You can also use FloatArray, DoubleArray, LongArray, ShortArray, ByteArray, CharArray, BooleanArray
val simpleIntegerArrayV1: IntArray = intArrayOf(1, 2, 3, 4, 5)
simpleIntegerArrayV1[0] = 10
// Or just use arrayOf
val simpleIntegerArrayV2: Array = arrayOf(1, 2, 3, 4, 5)
val simpleIntegerArrayV3: Array = Array(5) { i -> i + 1 }
val simpleIntegerArrayV4: Array = Array(5) { it + 1 }
val simpleIntegerArrayV5 = simpleIntegerArrayV4 + simpleIntegerArrayV3
val simpleIntegerArrayWithNullable: Array = arrayOf(1, 2, 3, 4, 5, null)
simpleIntegerArrayV2.forEach {
println(it)
}
simpleIntegerArrayV2.forEachIndexed { index, i ->
println("Index: $index, Value: $i")
}
println(simpleIntegerArrayV5.joinTo(StringBuilder(), separator = ", ", prefix = "[", postfix = "]"))
}
Some applications of Array in a real program: Storing the state of an object; Storing change history; Caching unprocessed data; ,,,
fun main() {
val greeting = "Hello"
val completeGreeting = "$greeting, Kotlin!"
println(completeGreeting)
// String Interpolation
val name = "DanTech0xFF"
println("Hello, $name!")
// Multiline Strings
val text = """
This is a multiline string.
It spans multiple lines.
"""
println(text)
// String Length
val textLength = "Hello, Kotlin Programming!"
println("Length of the string is ${textLength.length}")
// String to Int Conversion
val numberString = "123"
val number = numberString.toInt()
println(number + 1)
// String Comparison
val text1 = "Hello"
val text2 = "hello"
println(text1.equals(text2, ignoreCase = true))
// Substring
val substringText = "Hello, World!"
println(substringText.substring(0, 5))
// Replace
val replaceText = "Hello, Kotlin!"
println(replaceText.replace("Kotlin", "Kotlin Programming"))
}
Some applications of String in a program:
- Store JSON content, Database Query, File Content…
- Cache content of View displaying Text
List, Stack, Queue
Refer to the example code below for how to use List in Kotlin:
fun main() {
val numbers: List = listOf(1, 2, 3, 4, 5)
println(numbers[0]) // Output: 1
println(numbers[1]) // Output: 2
println(numbers.size) // Output: 5
println(numbers.contains(3)) // Output: true
println(numbers.indexOf(4)) // Output: 3
println(numbers.lastIndexOf(5)) // Output: 4
println(numbers.subList(1, 4)) // Output: [2, 3, 4]
println(numbers.isNotEmpty())
val mutableNumbers = mutableListOf(1, 2, 3, 4, 5) // numbers.toMutableList()
mutableNumbers.add(6)
mutableNumbers.removeAt(0)
mutableNumbers[1] = 10
println(mutableNumbers) // Output: [2, 10, 3, 4, 5, 6]
}
Refer to the code example below for how to use Stack, Queue:
fun main() {
// Deque is a double-ended queue that supports adding and removing elements from both ends
// support both mechanisms of stack and queue
val deque = ArrayDeque()
// Adding elements to the deque
deque.addFirst(1)
deque.addLast(2)
deque.addFirst(3)
deque.addLast(4)
println("Deque after adding elements: $deque")
// Removing elements from the deque
val removedFirst = deque.removeFirst()
val removedLast = deque.removeLast()
println("Removed first element: $removedFirst")
println("Removed last element: $removedLast")
println("Deque after removing elements: $deque")
// Iterating over the elements
println("Iterating over the elements:")
for (element in deque) {
println(element)
}
// Checking if deque contains a specific element
val containsThree = deque.contains(3)
println("Deque contains 3: $containsThree")
// Getting the size of the deque
val size = deque.size
println("Size of the deque: $size")
// Checking if the deque is empty
val isEmpty = deque.isEmpty()
println("Is deque empty: $isEmpty")
// Clearing the deque
deque.clear()
println("Deque after clearing: $deque")
}
Map, Set
Refer to the code example below for how to declare and use Map types in Kotlin:
fun main() {
val hashMap = mapOf(
"key1" to "value1",
"key2" to "value2",
"key3" to "value3"
) // Immutable Map
val mutableHashMap = mutableMapOf(
"key1" to "value1",
"key2" to "value2",
"key3" to "value3"
) // Mutable Map
val emptyHashMap = hashMapOf() // Mutable empty HashMap
val manualHashMap: HashMap = HashMap() // Mutable empty HashMap
val immutableHashMap: Map = HashMap() // Immutable empty HashMap
}
- Map and MutableMap are interfaces to represent the Mutability of Map
- HashMap is an Implementation of MutableMap
- Besides HashMap, we can also use other Implementations of MutableMap, for example: LinkedHashMap
Similar to Map and MutableMap, List and MutableList -> we have Set and MutableSet in Kotlin.
fun main() {
val hashSet = setOf("value1", "value2", "value3") // Immutable Set
val mutableHashSet = mutableSetOf("value1", "value2", "value3") // Mutable Set
val emptyHashSet = hashSetOf() // Mutable empty HashSet
val manualHashSet: HashSet = HashSet() // Mutable empty HashSet
val immutableHashSet: Set = HashSet() // Immutable empty HashSet
}
Through the above examples and knowledge, we can see that Kotlin is a very strict language in terms of syntax, through clearly defining Mutable and Immutable. Therefore, during work, you will avoid many unnecessary mistakes due to incorrect data changes and updates.