📘 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
A Kotlin Set is a generic unordered collection of elements which allows no duplicates.
Key points of Set:
- Methods in this interface supports only read-only access to the set; read/write access is supported through the MutableSet interface.
- Kotlin distinguishes between read-only and mutable sets. Read-only sets are created with setOf() and mutable set with mutableSetOf().
- MutableSet is a Set with write operations from MutableCollection.
- The default implementation of Set – LinkedHashSet – preserves the order of elements insertion. Hence, the functions that rely on the order, such as first() or last(), return predictable results on such sets.
package net.sourcecodeexamples.kotlin
fun main() {
// Set contains unique elements
val theSet = setOf("one", "two", "three", "one")
println(theSet)
println("The set contains ${theSet.size} elements.")
}
[one, two, three]
The set contains 3 elements.
Kotlin mutableSetOf()
package net.sourcecodeexamples.kotlin
fun main(args: Array < String > ) {
val nums = mutableSetOf(3, 4, 5)
nums.add(6)
nums.add(7)
nums.addAll(setOf(8, 9, 10))
println(nums)
nums.remove(10)
println(nums)
nums.retainAll(setOf(12, 14, 16, 18))
println(nums)
nums.clear()
if (nums.isEmpty()) println("The set is empty")
else println("The set is not epty")
}
[3, 4, 5, 6, 7, 8, 9, 10]
[3, 4, 5, 6, 7, 8, 9]
[]
The set is empty
Kotlin Set indexing
package net.sourcecodeexamples.kotlin
fun main() {
val fruits = setOf("banana", "mango", "apple", "orange", "banana")
val w1 = fruits.elementAt(0);
println(w1)
val i1 = fruits.indexOf("banana")
println("The first index of banana is $i1")
val i2 = fruits.lastIndexOf("banana")
println("The last index of banana is $i2")
}
banana
The first index of banana is 0
The last index of banana is 0
Kotlin Set count
package net.sourcecodeexamples.kotlin
fun main() {
val nums = setOf(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 5 elements
The size of the list is 5
There are 0 negative values
There are 3 even values
Kotlin Set first and last elements
package net.sourcecodeexamples.kotlin
fun main() {
val fruits = setOf("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
Kotlin Set iterate
- Using forEach() method
- Using for loop
- An alternative for cycle utilizes the size of the list
- Using forEachIndexed() method
- Using a Iterator and a while loop
package net.sourcecodeexamples.kotlin
fun main() {
val fruits = setOf("banana", "mango", "apple", "orange", "banana")
// 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.elementAt(i)} ")
}
println()
// using forEachIndexed() method
fruits.forEachIndexed({
i,
e - > println("fruits[$i] = $e")
})
val it: Iterator < String > = fruits.asIterable().iterator();
while (it.hasNext()) {
val e = it.next()
print("$e ")
}
println()
}
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 Set Sort Example - Ascending and Descending Order
package net.sourcecodeexamples.kotlin
fun main() {
val nums = setOf(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 Set contains
package net.sourcecodeexamples.kotlin
fun main() {
val nums = setOf(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 Set union
package net.sourcecodeexamples.kotlin
fun main(args: Array<String>) {
val nums = setOf(1, 2, 3, 4,5)
val nums2 = setOf(3, 4, 5,6,7,8,9)
val nums3 = nums.union(nums2)
println(nums3)
}
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Kotlin Set filter
package net.sourcecodeexamples.kotlin
fun main(args: Array<String>) {
val fruits = setOf("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 Set any
package net.sourcecodeexamples.kotlin
fun main() {
val nums = setOf(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 Set all
package net.sourcecodeexamples.kotlin
fun main() {
val nums = setOf(1,2,3,4,5,6,7,8,9)
val nums2 = setOf(-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
Comments
Post a Comment
Leave Comment