📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Key points of the List:
- Methods in the List interface support only read-only access to the list; read/write access is supported through the MutableList interface.
- Kotlin distinguishes between read-only and mutable lists. Read-only lists are created with the listOf() method and mutable lists with the mutableListOf() method.
- In Kotlin, the default implementation of List is ArrayList which you can think of as a resizable array.
- MutableList is a List with list-specific write operations, for example, to add or remove an element at a specific position.
Kotlin listOf()
package net.sourcecodeexamples.kotlin
fun main() {
val words = listOf("Ab", "cup", "dog", "spectacles")
println("The list contains ${words.size} elements.")
}
The list contains 4 elements.
Kotlin listOf() and mutableListOf() Example
We can create a simple read-only List using method listOf() and read-write MutableList using mutableListOf():package net.sourcecodeexamples.kotlin
fun main() {
val theList = listOf("one", "two", "three")
println(theList)
val theMutableList = mutableListOf("one", "two", "three")
println(theMutableList)
}
[one, two, three]
[one, two, three]
Kotlin List Basic Examples
package net.sourcecodeexamples.kotlin
fun main() {
val nums = listOf(1, 15, 13, 8, 1, 19, 6, 12)
val len = nums.count()
val max = nums.max()
val min = nums.min()
val sum = nums.sum()
val avg = nums.average()
val msg = """
max: $max, min: $min,
count: $len, sum: $sum,
average: $avg
"""
println(msg.trimIndent())
}
max: 19, min: 1,
count: 8, sum: 75,
average: 9.375
Kotlin List Indexing
fun main() {
val words = listOf("pen", "cup", "dog", "person",
"cement", "coal", "spectacles", "cup", "bread")
val w1 = words.get(0)
println(w1)
val w2 = words[0]
println(w2)
val i1 = words.indexOf("cup")
println("The first index of cup is $i1")
val i2 = words.lastIndexOf("cup")
println("The last index of cup is $i2")
val i3 = words.lastIndex
println("The last index of the list is $i3")
}
pen
pen
The first index of cup is 1
The last index of cup is 7
The last index of the list is 8
This is the output.
Kotlin List count
package net.sourcecodeexamples
fun main() {
val nums = listOf(12, 1,2,5,4,2)
val len = nums.count()
println("There are $len elements")
val size = nums.size
println("The size of the list is $size")
val n1 = nums.count { e -> e < 0 }
println("There are $n1 negative values")
val n2 = nums.count { e -> e % 2 == 0 }
println("There are $n2 even values")
}
There are 6 elements
The size of the list is 6
There are 0 negative values
There are 4 even values
Kotlin List first and last elements
package net.sourcecodeexamples.kotlin
fun main() {
val fruits = listOf("banana", "mango", "apple", "orange")
val w1 = fruits.first()
println(w1)
val w2 = fruits.last()
println(w2)
val w3 = fruits.findLast { w -> w.startsWith('a') }
println(w3)
val w4 = fruits.first { w -> w.startsWith('o') }
println(w4)
}
banana
orange
apple
orange
val w1 = words.first()
val w2 = words.last()
val w3 = words.findLast { w -> w.startsWith('a') }
val w4 = words.first { w -> w.startsWith('o') }
Kotlin List iterate
- Using forEach() method
- Using for loop
- An alternative for cycle utilizes the size of the list
- Using forEachIndexed() method
- Using a ListIterator and a while loop
package net.sourcecodeexamples.kotlin
fun main() {
val fruits = listOf("banana", "mango", "apple", "orange")
// using forEach() method
fruits.forEach { e -> print("$e ") }
println()
// using for loop
for (fruit in fruits) {
print("$fruit ")
}
println()
// An alternative for cycle utilizes the size of the list
for (i in 0 until fruits.size) {
print("${fruits[i]} ")
}
println()
// using forEachIndexed() method
fruits.forEachIndexed({ i, e -> println("fruits[$i] = $e") })
// using a ListIterator and a while loop
val it: ListIterator<String> = fruits.listIterator()
while (it.hasNext()) {
val e = it.next()
print("$e ")
}
println()
}
Output
banana mango apple orange
banana mango apple orange
banana mango apple orange
fruits[0] = banana
fruits[1] = mango
fruits[2] = apple
fruits[3] = orange
banana mango apple orange
Kotlin List Sort - Ascending and Descending Order
package net.sourcecodeexamples.kotlin
fun main() {
val nums = listOf(10, 5, 3, 4, 2, 1, 11, 14, 12)
val sortAsc = nums.sorted()
println("sortAsc -> " + sortAsc)
val sortDesc = nums.sortedDescending()
println("sortDesc -> " + sortDesc)
val revNums = nums.reversed()
println("revNums -> " + revNums)
}
sortAsc -> [1, 2, 3, 4, 5, 10, 11, 12, 14]
sortDesc -> [14, 12, 11, 10, 5, 4, 3, 2, 1]
revNums -> [12, 14, 11, 1, 2, 4, 3, 5, 10]
Kotlin List contains()
package net.sourcecodeexamples.kotlin
fun main() {
val nums = listOf(1, 2, 3, 7, 6, 5, 4)
val r = nums.contains(4)
if (r) {
println("The list contains 4")
} else {
println("The list does not contain 4")
}
val r2 = nums.containsAll(listOf(1, 6))
if (r2) {
println("The list contains 1 and 6")
} else {
println("The list does not contain 1 and 6")
}
}
The list contains 4
The list contains 1 and 6
Kotlin List contains()
package net.sourcecodeexamples.kotlin
fun main() {
val nums = listOf(1, 2, 3, 4, 5, 6)
val nums2 = nums.slice(1..3)
println(nums2)
val nums3 = nums.slice(listOf(3, 4, 5))
println(nums3)
}
[2, 3, 4]
[4, 5, 6]
Kotlin List Filter Example
The following example presents the filtering operation on Kotlin lists.
package net.sourcecodeexamples.kotlin
fun main(args: Array<String>) {
val fruits = listOf("banana", "mango", "apple", "orange")
val fruits1 = fruits.filter { e -> e.length == 5 }
fruits1.forEach { e -> print("$e ") }
println()
val fruits2 = fruits.filterNot { e -> e.length == 5 }
fruits2.forEach { e -> print("$e ") }
println()
}
mango apple
banana orange
Kotlin List any
package net.sourcecodeexamples.kotlin
fun main() {
val nums = listOf(1,2,3,4,5,6,7,-1,-2)
val r = nums.any { e -> e > 10 }
if (r) {
println("There is a value greater than ten")
} else {
println("There is no value greater than ten")
}
val r2 = nums.any { e -> e < 0 }
if (r2) {
println("There is a negative value")
} else {
println("There is no negative value")
}
}
There is no value greater than ten
There is a negative value
Kotlin List all
package net.sourcecodeexamples.kotlin fun main() { val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9) val nums2 = listOf(-3, -4, -2, -5, -7, -8) // testing for positive only values val r = nums.all { e - > e > 0 } if (r) { println("nums list contains only positive values") } else { println("nums list does not contain only positive values") } // testing for negative only values val r2 = nums2.all { e - > e < 0 } if (r2) { println("nums2 list contains only negative values") } else { println("nums2 list does not contain only negative values") } }
nums list contains only positive values
nums2 list contains only negative values
Kotlin List drop
package net.sourcecodeexamples.kotlin
fun main() {
val nums = listOf(1,2,-1,-2,3,4,5,6,7,8,9,10)
val nums2 = nums.drop(3)
println(nums2)
val nums3 = nums.dropLast(3)
println(nums3)
val nums4 = nums.sorted().dropWhile { e -> e < 0 }
println(nums4)
val nums5 = nums.sorted().dropLastWhile { e -> e > 0 }
println(nums5)
}
[-2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, -1, -2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[-2, -1]
Comments
Post a Comment
Leave Comment